1/*
2 * Written by Doug Lea with assistance from members of JCP JSR-166
3 * Expert Group and released to the public domain, as explained at
4 * http://creativecommons.org/publicdomain/zero/1.0/
5 * Other contributors include Andrew Wright, Jeffrey Hayes,
6 * Pat Fisher, Mike Judd.
7 */
8
9
10package jsr166;
11
12import static java.util.concurrent.TimeUnit.MILLISECONDS;
13import static java.util.concurrent.TimeUnit.MINUTES;
14import static java.util.concurrent.TimeUnit.NANOSECONDS;
15
16import java.io.ByteArrayInputStream;
17import java.io.ByteArrayOutputStream;
18import java.io.ObjectInputStream;
19import java.io.ObjectOutputStream;
20import java.lang.reflect.Constructor;
21import java.lang.reflect.Method;
22import java.lang.reflect.Modifier;
23 import java.security.CodeSource;
24import java.security.Permission;
25import java.security.PermissionCollection;
26import java.security.Permissions;
27import java.security.Policy;
28import java.security.ProtectionDomain;
29import java.security.SecurityPermission;
30import java.util.ArrayList;
31import java.util.Arrays;
32import java.util.Date;
33import java.util.Enumeration;
34import java.util.Iterator;
35import java.util.List;
36import java.util.NoSuchElementException;
37import java.util.PropertyPermission;
38import java.util.concurrent.BlockingQueue;
39import java.util.concurrent.Callable;
40import java.util.concurrent.CountDownLatch;
41import java.util.concurrent.CyclicBarrier;
42import java.util.concurrent.ExecutionException;
43import java.util.concurrent.Executors;
44import java.util.concurrent.ExecutorService;
45import java.util.concurrent.ForkJoinPool;
46import java.util.concurrent.Future;
47import java.util.concurrent.RecursiveAction;
48import java.util.concurrent.RecursiveTask;
49import java.util.concurrent.RejectedExecutionHandler;
50import java.util.concurrent.Semaphore;
51import java.util.concurrent.ThreadFactory;
52import java.util.concurrent.ThreadPoolExecutor;
53import java.util.concurrent.TimeoutException;
54import java.util.concurrent.atomic.AtomicBoolean;
55import java.util.concurrent.atomic.AtomicReference;
56import java.util.regex.Matcher;
57import java.util.regex.Pattern;
58
59import junit.framework.AssertionFailedError;
60import junit.framework.Test;
61import junit.framework.TestCase;
62import junit.framework.TestResult;
63import junit.framework.TestSuite;
64
65/**
66 * Base class for JSR166 Junit TCK tests.  Defines some constants,
67 * utility methods and classes, as well as a simple framework for
68 * helping to make sure that assertions failing in generated threads
69 * cause the associated test that generated them to itself fail (which
70 * JUnit does not otherwise arrange).  The rules for creating such
71 * tests are:
72 *
73 * <ol>
74 *
75 * <li>All assertions in code running in generated threads must use
76 * the forms {@link #threadFail}, {@link #threadAssertTrue}, {@link
77 * #threadAssertEquals}, or {@link #threadAssertNull}, (not
78 * {@code fail}, {@code assertTrue}, etc.) It is OK (but not
79 * particularly recommended) for other code to use these forms too.
80 * Only the most typically used JUnit assertion methods are defined
81 * this way, but enough to live with.
82 *
83 * <li>If you override {@link #setUp} or {@link #tearDown}, make sure
84 * to invoke {@code super.setUp} and {@code super.tearDown} within
85 * them. These methods are used to clear and check for thread
86 * assertion failures.
87 *
88 * <li>All delays and timeouts must use one of the constants {@code
89 * SHORT_DELAY_MS}, {@code SMALL_DELAY_MS}, {@code MEDIUM_DELAY_MS},
90 * {@code LONG_DELAY_MS}. The idea here is that a SHORT is always
91 * discriminable from zero time, and always allows enough time for the
92 * small amounts of computation (creating a thread, calling a few
93 * methods, etc) needed to reach a timeout point. Similarly, a SMALL
94 * is always discriminable as larger than SHORT and smaller than
95 * MEDIUM.  And so on. These constants are set to conservative values,
96 * but even so, if there is ever any doubt, they can all be increased
97 * in one spot to rerun tests on slower platforms.
98 *
99 * <li>All threads generated must be joined inside each test case
100 * method (or {@code fail} to do so) before returning from the
101 * method. The {@code joinPool} method can be used to do this when
102 * using Executors.
103 *
104 * </ol>
105 *
106 * <p><b>Other notes</b>
107 * <ul>
108 *
109 * <li>Usually, there is one testcase method per JSR166 method
110 * covering "normal" operation, and then as many exception-testing
111 * methods as there are exceptions the method can throw. Sometimes
112 * there are multiple tests per JSR166 method when the different
113 * "normal" behaviors differ significantly. And sometimes testcases
114 * cover multiple methods when they cannot be tested in isolation.
115 *
116 * <li>The documentation style for testcases is to provide as javadoc
117 * a simple sentence or two describing the property that the testcase
118 * method purports to test. The javadocs do not say anything about how
119 * the property is tested. To find out, read the code.
120 *
121 * <li>These tests are "conformance tests", and do not attempt to
122 * test throughput, latency, scalability or other performance factors
123 * (see the separate "jtreg" tests for a set intended to check these
124 * for the most central aspects of functionality.) So, most tests use
125 * the smallest sensible numbers of threads, collection sizes, etc
126 * needed to check basic conformance.
127 *
128 * <li>The test classes currently do not declare inclusion in
129 * any particular package to simplify things for people integrating
130 * them in TCK test suites.
131 *
132 * <li>As a convenience, the {@code main} of this class (JSR166TestCase)
133 * runs all JSR166 unit tests.
134 *
135 * </ul>
136 */
137public class JSR166TestCase extends TestCase {
138    private static final boolean useSecurityManager =
139        Boolean.getBoolean("jsr166.useSecurityManager");
140
141    protected static final boolean expensiveTests =
142        Boolean.getBoolean("jsr166.expensiveTests");
143
144    /**
145     * If true, also run tests that are not part of the official tck
146     * because they test unspecified implementation details.
147     */
148    protected static final boolean testImplementationDetails =
149        Boolean.getBoolean("jsr166.testImplementationDetails");
150
151    /**
152     * If true, report on stdout all "slow" tests, that is, ones that
153     * take more than profileThreshold milliseconds to execute.
154     */
155    private static final boolean profileTests =
156        Boolean.getBoolean("jsr166.profileTests");
157
158    /**
159     * The number of milliseconds that tests are permitted for
160     * execution without being reported, when profileTests is set.
161     */
162    private static final long profileThreshold =
163        Long.getLong("jsr166.profileThreshold", 100);
164
165    /**
166     * The number of repetitions per test (for tickling rare bugs).
167     */
168    private static final int runsPerTest =
169        Integer.getInteger("jsr166.runsPerTest", 1);
170
171    /**
172     * The number of repetitions of the test suite (for finding leaks?).
173     */
174    private static final int suiteRuns =
175        Integer.getInteger("jsr166.suiteRuns", 1);
176
177    private static float systemPropertyValue(String name, float defaultValue) {
178        String floatString = System.getProperty(name);
179        if (floatString == null)
180            return defaultValue;
181        try {
182            return Float.parseFloat(floatString);
183        } catch (NumberFormatException ex) {
184            throw new IllegalArgumentException(
185                String.format("Bad float value in system property %s=%s",
186                              name, floatString));
187        }
188    }
189
190    /**
191     * The scaling factor to apply to standard delays used in tests.
192     */
193    private static final float delayFactor =
194        systemPropertyValue("jsr166.delay.factor", 1.0f);
195
196    /**
197     * The timeout factor as used in the jtreg test harness.
198     * See: http://openjdk.java.net/jtreg/tag-spec.html
199     */
200    private static final float jtregTestTimeoutFactor
201        = systemPropertyValue("test.timeout.factor", 1.0f);
202
203    public JSR166TestCase() { super(); }
204    public JSR166TestCase(String name) { super(name); }
205
206    /**
207     * A filter for tests to run, matching strings of the form
208     * methodName(className), e.g. "testInvokeAll5(ForkJoinPoolTest)"
209     * Usefully combined with jsr166.runsPerTest.
210     */
211    private static final Pattern methodFilter = methodFilter();
212
213    private static Pattern methodFilter() {
214        String regex = System.getProperty("jsr166.methodFilter");
215        return (regex == null) ? null : Pattern.compile(regex);
216    }
217
218    // Instrumentation to debug very rare, but very annoying hung test runs.
219    static volatile TestCase currentTestCase;
220    // static volatile int currentRun = 0;
221    static {
222        Runnable checkForWedgedTest = new Runnable() { public void run() {
223            // Avoid spurious reports with enormous runsPerTest.
224            // A single test case run should never take more than 1 second.
225            // But let's cap it at the high end too ...
226            final int timeoutMinutes =
227                Math.min(15, Math.max(runsPerTest / 60, 1));
228            for (TestCase lastTestCase = currentTestCase;;) {
229                try { MINUTES.sleep(timeoutMinutes); }
230                catch (InterruptedException unexpected) { break; }
231                if (lastTestCase == currentTestCase) {
232                    System.err.printf(
233                        "Looks like we're stuck running test: %s%n",
234                        lastTestCase);
235//                     System.err.printf(
236//                         "Looks like we're stuck running test: %s (%d/%d)%n",
237//                         lastTestCase, currentRun, runsPerTest);
238//                     System.err.println("availableProcessors=" +
239//                         Runtime.getRuntime().availableProcessors());
240//                     System.err.printf("cpu model = %s%n", cpuModel());
241                    dumpTestThreads();
242                    // one stack dump is probably enough; more would be spam
243                    break;
244                }
245                lastTestCase = currentTestCase;
246            }}};
247        Thread thread = new Thread(checkForWedgedTest, "checkForWedgedTest");
248        thread.setDaemon(true);
249        thread.start();
250    }
251
252//     public static String cpuModel() {
253//         try {
254//             Matcher matcher = Pattern.compile("model name\\s*: (.*)")
255//                 .matcher(new String(
256//                      Files.readAllBytes(Paths.get("/proc/cpuinfo")), "UTF-8"));
257//             matcher.find();
258//             return matcher.group(1);
259//         } catch (Exception ex) { return null; }
260//     }
261
262    public void runBare() throws Throwable {
263        currentTestCase = this;
264        if (methodFilter == null
265            || methodFilter.matcher(toString()).find())
266            super.runBare();
267    }
268
269    protected void runTest() throws Throwable {
270        for (int i = 0; i < runsPerTest; i++) {
271            // currentRun = i;
272            if (profileTests)
273                runTestProfiled();
274            else
275                super.runTest();
276        }
277    }
278
279    protected void runTestProfiled() throws Throwable {
280        for (int i = 0; i < 2; i++) {
281            long startTime = System.nanoTime();
282            super.runTest();
283            long elapsedMillis = millisElapsedSince(startTime);
284            if (elapsedMillis < profileThreshold)
285                break;
286            // Never report first run of any test; treat it as a
287            // warmup run, notably to trigger all needed classloading,
288            if (i > 0)
289                System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
290        }
291    }
292
293    /**
294     * Runs all JSR166 unit tests using junit.textui.TestRunner.
295     */
296    // android-note: Removed because no junit.textui
297    // public static void main(String[] args) {
298    //     main(suite(), args);
299    // }
300
301    // static class PithyResultPrinter extends junit.textui.ResultPrinter {
302    //     PithyResultPrinter(java.io.PrintStream writer) { super(writer); }
303    //     long runTime;
304    //     public void startTest(Test test) {}
305    //     protected void printHeader(long runTime) {
306    //         this.runTime = runTime; // defer printing for later
307    //     }
308    //     protected void printFooter(TestResult result) {
309    //         if (result.wasSuccessful()) {
310    //             getWriter().println("OK (" + result.runCount() + " tests)"
311    //                 + "  Time: " + elapsedTimeAsString(runTime));
312    //         } else {
313    //             getWriter().println("Time: " + elapsedTimeAsString(runTime));
314    //             super.printFooter(result);
315    //         }
316    //     }
317    // }
318
319    /**
320     * Returns a TestRunner that doesn't bother with unnecessary
321     * fluff, like printing a "." for each test case.
322     */
323    // static junit.textui.TestRunner newPithyTestRunner() {
324    //     junit.textui.TestRunner runner = new junit.textui.TestRunner();
325    //     runner.setPrinter(new PithyResultPrinter(System.out));
326    //     return runner;
327    // }
328
329    /**
330     * Runs all unit tests in the given test suite.
331     * Actual behavior influenced by jsr166.* system properties.
332     */
333    // static void main(Test suite, String[] args) {
334    //     if (useSecurityManager) {
335    //         System.err.println("Setting a permissive security manager");
336    //         Policy.setPolicy(permissivePolicy());
337    //         System.setSecurityManager(new SecurityManager());
338    //     }
339    //     for (int i = 0; i < suiteRuns; i++) {
340    //         TestResult result = newPithyTestRunner().doRun(suite);
341    //         if (!result.wasSuccessful())
342    //             System.exit(1);
343    //         System.gc();
344    //         System.runFinalization();
345    //     }
346    // }
347
348    public static TestSuite newTestSuite(Object... suiteOrClasses) {
349        TestSuite suite = new TestSuite();
350        for (Object suiteOrClass : suiteOrClasses) {
351            if (suiteOrClass instanceof TestSuite)
352                suite.addTest((TestSuite) suiteOrClass);
353            else if (suiteOrClass instanceof Class)
354                suite.addTest(new TestSuite((Class<?>) suiteOrClass));
355            else
356                throw new ClassCastException("not a test suite or class");
357        }
358        return suite;
359    }
360
361    public static void addNamedTestClasses(TestSuite suite,
362                                           String... testClassNames) {
363        for (String testClassName : testClassNames) {
364            try {
365                Class<?> testClass = Class.forName(testClassName);
366                Method m = testClass.getDeclaredMethod("suite",
367                                                       new Class<?>[0]);
368                suite.addTest(newTestSuite((Test)m.invoke(null)));
369            } catch (Exception e) {
370                throw new Error("Missing test class", e);
371            }
372        }
373    }
374
375    public static final double JAVA_CLASS_VERSION;
376    public static final String JAVA_SPECIFICATION_VERSION;
377    static {
378        try {
379            JAVA_CLASS_VERSION = java.security.AccessController.doPrivileged(
380                new java.security.PrivilegedAction<Double>() {
381                public Double run() {
382                    return Double.valueOf(System.getProperty("java.class.version"));}});
383            JAVA_SPECIFICATION_VERSION = java.security.AccessController.doPrivileged(
384                new java.security.PrivilegedAction<String>() {
385                public String run() {
386                    return System.getProperty("java.specification.version");}});
387        } catch (Throwable t) {
388            throw new Error(t);
389        }
390    }
391
392    public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
393    public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
394    public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
395    public static boolean atLeastJava9() {
396        return JAVA_CLASS_VERSION >= 53.0
397            // As of 2015-09, java9 still uses 52.0 class file version
398            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?(9|[0-9][0-9])$");
399    }
400    public static boolean atLeastJava10() {
401        return JAVA_CLASS_VERSION >= 54.0
402            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?[0-9][0-9]$");
403    }
404
405    /**
406     * Collects all JSR166 unit tests as one suite.
407     */
408    // android-note: Removed because the CTS runner does a bad job of
409    // public static Test suite() {
410    //     // Java7+ test classes
411    //     TestSuite suite = newTestSuite(
412    //         ForkJoinPoolTest.suite(),
413    //         ForkJoinTaskTest.suite(),
414    //         RecursiveActionTest.suite(),
415    //         RecursiveTaskTest.suite(),
416    //         LinkedTransferQueueTest.suite(),
417    //         PhaserTest.suite(),
418    //         ThreadLocalRandomTest.suite(),
419    //         AbstractExecutorServiceTest.suite(),
420    //         AbstractQueueTest.suite(),
421    //         AbstractQueuedSynchronizerTest.suite(),
422    //         AbstractQueuedLongSynchronizerTest.suite(),
423    //         ArrayBlockingQueueTest.suite(),
424    //         ArrayDequeTest.suite(),
425    //         AtomicBooleanTest.suite(),
426    //         AtomicIntegerArrayTest.suite(),
427    //         AtomicIntegerFieldUpdaterTest.suite(),
428    //         AtomicIntegerTest.suite(),
429    //         AtomicLongArrayTest.suite(),
430    //         AtomicLongFieldUpdaterTest.suite(),
431    //         AtomicLongTest.suite(),
432    //         AtomicMarkableReferenceTest.suite(),
433    //         AtomicReferenceArrayTest.suite(),
434    //         AtomicReferenceFieldUpdaterTest.suite(),
435    //         AtomicReferenceTest.suite(),
436    //         AtomicStampedReferenceTest.suite(),
437    //         ConcurrentHashMapTest.suite(),
438    //         ConcurrentLinkedDequeTest.suite(),
439    //         ConcurrentLinkedQueueTest.suite(),
440    //         ConcurrentSkipListMapTest.suite(),
441    //         ConcurrentSkipListSubMapTest.suite(),
442    //         ConcurrentSkipListSetTest.suite(),
443    //         ConcurrentSkipListSubSetTest.suite(),
444    //         CopyOnWriteArrayListTest.suite(),
445    //         CopyOnWriteArraySetTest.suite(),
446    //         CountDownLatchTest.suite(),
447    //         CyclicBarrierTest.suite(),
448    //         DelayQueueTest.suite(),
449    //         EntryTest.suite(),
450    //         ExchangerTest.suite(),
451    //         ExecutorsTest.suite(),
452    //         ExecutorCompletionServiceTest.suite(),
453    //         FutureTaskTest.suite(),
454    //         LinkedBlockingDequeTest.suite(),
455    //         LinkedBlockingQueueTest.suite(),
456    //         LinkedListTest.suite(),
457    //         LockSupportTest.suite(),
458    //         PriorityBlockingQueueTest.suite(),
459    //         PriorityQueueTest.suite(),
460    //         ReentrantLockTest.suite(),
461    //         ReentrantReadWriteLockTest.suite(),
462    //         ScheduledExecutorTest.suite(),
463    //         ScheduledExecutorSubclassTest.suite(),
464    //         SemaphoreTest.suite(),
465    //         SynchronousQueueTest.suite(),
466    //         SystemTest.suite(),
467    //         ThreadLocalTest.suite(),
468    //         ThreadPoolExecutorTest.suite(),
469    //         ThreadPoolExecutorSubclassTest.suite(),
470    //         ThreadTest.suite(),
471    //         TimeUnitTest.suite(),
472    //         TreeMapTest.suite(),
473    //         TreeSetTest.suite(),
474    //         TreeSubMapTest.suite(),
475    //         TreeSubSetTest.suite());
476
477    //     // Java8+ test classes
478    //     if (atLeastJava8()) {
479    //         String[] java8TestClassNames = {
480    //             "Atomic8Test",
481    //             "CompletableFutureTest",
482    //             "ConcurrentHashMap8Test",
483    //             "CountedCompleterTest",
484    //             "DoubleAccumulatorTest",
485    //             "DoubleAdderTest",
486    //             "ForkJoinPool8Test",
487    //             "ForkJoinTask8Test",
488    //             "LongAccumulatorTest",
489    //             "LongAdderTest",
490    //             "SplittableRandomTest",
491    //             "StampedLockTest",
492    //             "SubmissionPublisherTest",
493    //             "ThreadLocalRandom8Test",
494    //         };
495    //         addNamedTestClasses(suite, java8TestClassNames);
496    //     }
497
498    //     // Java9+ test classes
499    //     if (atLeastJava9()) {
500    //         String[] java9TestClassNames = {
501    //             // Currently empty, but expecting varhandle tests
502    //         };
503    //         addNamedTestClasses(suite, java9TestClassNames);
504    //     }
505
506    //     return suite;
507    // }
508
509    /** Returns list of junit-style test method names in given class. */
510    public static ArrayList<String> testMethodNames(Class<?> testClass) {
511        Method[] methods = testClass.getDeclaredMethods();
512        ArrayList<String> names = new ArrayList<String>(methods.length);
513        for (Method method : methods) {
514            if (method.getName().startsWith("test")
515                && Modifier.isPublic(method.getModifiers())
516                // method.getParameterCount() requires jdk8+
517                && method.getParameterTypes().length == 0) {
518                names.add(method.getName());
519            }
520        }
521        return names;
522    }
523
524    /**
525     * Returns junit-style testSuite for the given test class, but
526     * parameterized by passing extra data to each test.
527     */
528    public static <ExtraData> Test parameterizedTestSuite
529        (Class<? extends JSR166TestCase> testClass,
530         Class<ExtraData> dataClass,
531         ExtraData data) {
532        try {
533            TestSuite suite = new TestSuite();
534            Constructor c =
535                testClass.getDeclaredConstructor(dataClass, String.class);
536            for (String methodName : testMethodNames(testClass))
537                suite.addTest((Test) c.newInstance(data, methodName));
538            return suite;
539        } catch (Exception e) {
540            throw new Error(e);
541        }
542    }
543
544    /**
545     * Returns junit-style testSuite for the jdk8 extension of the
546     * given test class, but parameterized by passing extra data to
547     * each test.  Uses reflection to allow compilation in jdk7.
548     */
549    public static <ExtraData> Test jdk8ParameterizedTestSuite
550        (Class<? extends JSR166TestCase> testClass,
551         Class<ExtraData> dataClass,
552         ExtraData data) {
553        if (atLeastJava8()) {
554            String name = testClass.getName();
555            String name8 = name.replaceAll("Test$", "8Test");
556            if (name.equals(name8)) throw new Error(name);
557            try {
558                return (Test)
559                    Class.forName(name8)
560                    .getMethod("testSuite", new Class[] { dataClass })
561                    .invoke(null, data);
562            } catch (Exception e) {
563                throw new Error(e);
564            }
565        } else {
566            return new TestSuite();
567        }
568    }
569
570    // Delays for timing-dependent tests, in milliseconds.
571
572    public static long SHORT_DELAY_MS;
573    public static long SMALL_DELAY_MS;
574    public static long MEDIUM_DELAY_MS;
575    public static long LONG_DELAY_MS;
576
577    /**
578     * Returns the shortest timed delay. This can be scaled up for
579     * slow machines using the jsr166.delay.factor system property,
580     * or via jtreg's -timeoutFactor: flag.
581     * http://openjdk.java.net/jtreg/command-help.html
582     */
583    protected long getShortDelay() {
584        return (long) (50 * delayFactor * jtregTestTimeoutFactor);
585    }
586
587    /**
588     * Sets delays as multiples of SHORT_DELAY.
589     */
590    protected void setDelays() {
591        SHORT_DELAY_MS = getShortDelay();
592        SMALL_DELAY_MS  = SHORT_DELAY_MS * 5;
593        MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
594        LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
595    }
596
597    /**
598     * Returns a timeout in milliseconds to be used in tests that
599     * verify that operations block or time out.
600     */
601    long timeoutMillis() {
602        return SHORT_DELAY_MS / 4;
603    }
604
605    /**
606     * Returns a new Date instance representing a time at least
607     * delayMillis milliseconds in the future.
608     */
609    Date delayedDate(long delayMillis) {
610        // Add 1 because currentTimeMillis is known to round into the past.
611        return new Date(System.currentTimeMillis() + delayMillis + 1);
612    }
613
614    /**
615     * The first exception encountered if any threadAssertXXX method fails.
616     */
617    private final AtomicReference<Throwable> threadFailure
618        = new AtomicReference<Throwable>(null);
619
620    /**
621     * Records an exception so that it can be rethrown later in the test
622     * harness thread, triggering a test case failure.  Only the first
623     * failure is recorded; subsequent calls to this method from within
624     * the same test have no effect.
625     */
626    public void threadRecordFailure(Throwable t) {
627        System.err.println(t);
628        dumpTestThreads();
629        threadFailure.compareAndSet(null, t);
630    }
631
632    public void setUp() {
633        setDelays();
634    }
635
636    void tearDownFail(String format, Object... args) {
637        String msg = toString() + ": " + String.format(format, args);
638        System.err.println(msg);
639        dumpTestThreads();
640        throw new AssertionFailedError(msg);
641    }
642
643    /**
644     * Extra checks that get done for all test cases.
645     *
646     * Triggers test case failure if any thread assertions have failed,
647     * by rethrowing, in the test harness thread, any exception recorded
648     * earlier by threadRecordFailure.
649     *
650     * Triggers test case failure if interrupt status is set in the main thread.
651     */
652    public void tearDown() throws Exception {
653        Throwable t = threadFailure.getAndSet(null);
654        if (t != null) {
655            if (t instanceof Error)
656                throw (Error) t;
657            else if (t instanceof RuntimeException)
658                throw (RuntimeException) t;
659            else if (t instanceof Exception)
660                throw (Exception) t;
661            else {
662                AssertionFailedError afe =
663                    new AssertionFailedError(t.toString());
664                afe.initCause(t);
665                throw afe;
666            }
667        }
668
669        if (Thread.interrupted())
670            tearDownFail("interrupt status set in main thread");
671
672        checkForkJoinPoolThreadLeaks();
673    }
674
675    /**
676     * Finds missing PoolCleaners
677     */
678    void checkForkJoinPoolThreadLeaks() throws InterruptedException {
679        Thread[] survivors = new Thread[7];
680        int count = Thread.enumerate(survivors);
681        for (int i = 0; i < count; i++) {
682            Thread thread = survivors[i];
683            String name = thread.getName();
684            if (name.startsWith("ForkJoinPool-")) {
685                // give thread some time to terminate
686                thread.join(LONG_DELAY_MS);
687                if (thread.isAlive())
688                    tearDownFail("Found leaked ForkJoinPool thread thread=%s",
689                                 thread);
690            }
691        }
692
693        if (!ForkJoinPool.commonPool()
694            .awaitQuiescence(LONG_DELAY_MS, MILLISECONDS))
695            tearDownFail("ForkJoin common pool thread stuck");
696    }
697
698    /**
699     * Just like fail(reason), but additionally recording (using
700     * threadRecordFailure) any AssertionFailedError thrown, so that
701     * the current testcase will fail.
702     */
703    public void threadFail(String reason) {
704        try {
705            fail(reason);
706        } catch (AssertionFailedError t) {
707            threadRecordFailure(t);
708            throw t;
709        }
710    }
711
712    /**
713     * Just like assertTrue(b), but additionally recording (using
714     * threadRecordFailure) any AssertionFailedError thrown, so that
715     * the current testcase will fail.
716     */
717    public void threadAssertTrue(boolean b) {
718        try {
719            assertTrue(b);
720        } catch (AssertionFailedError t) {
721            threadRecordFailure(t);
722            throw t;
723        }
724    }
725
726    /**
727     * Just like assertFalse(b), but additionally recording (using
728     * threadRecordFailure) any AssertionFailedError thrown, so that
729     * the current testcase will fail.
730     */
731    public void threadAssertFalse(boolean b) {
732        try {
733            assertFalse(b);
734        } catch (AssertionFailedError t) {
735            threadRecordFailure(t);
736            throw t;
737        }
738    }
739
740    /**
741     * Just like assertNull(x), but additionally recording (using
742     * threadRecordFailure) any AssertionFailedError thrown, so that
743     * the current testcase will fail.
744     */
745    public void threadAssertNull(Object x) {
746        try {
747            assertNull(x);
748        } catch (AssertionFailedError t) {
749            threadRecordFailure(t);
750            throw t;
751        }
752    }
753
754    /**
755     * Just like assertEquals(x, y), but additionally recording (using
756     * threadRecordFailure) any AssertionFailedError thrown, so that
757     * the current testcase will fail.
758     */
759    public void threadAssertEquals(long x, long y) {
760        try {
761            assertEquals(x, y);
762        } catch (AssertionFailedError t) {
763            threadRecordFailure(t);
764            throw t;
765        }
766    }
767
768    /**
769     * Just like assertEquals(x, y), but additionally recording (using
770     * threadRecordFailure) any AssertionFailedError thrown, so that
771     * the current testcase will fail.
772     */
773    public void threadAssertEquals(Object x, Object y) {
774        try {
775            assertEquals(x, y);
776        } catch (AssertionFailedError fail) {
777            threadRecordFailure(fail);
778            throw fail;
779        } catch (Throwable fail) {
780            threadUnexpectedException(fail);
781        }
782    }
783
784    /**
785     * Just like assertSame(x, y), but additionally recording (using
786     * threadRecordFailure) any AssertionFailedError thrown, so that
787     * the current testcase will fail.
788     */
789    public void threadAssertSame(Object x, Object y) {
790        try {
791            assertSame(x, y);
792        } catch (AssertionFailedError fail) {
793            threadRecordFailure(fail);
794            throw fail;
795        }
796    }
797
798    /**
799     * Calls threadFail with message "should throw exception".
800     */
801    public void threadShouldThrow() {
802        threadFail("should throw exception");
803    }
804
805    /**
806     * Calls threadFail with message "should throw" + exceptionName.
807     */
808    public void threadShouldThrow(String exceptionName) {
809        threadFail("should throw " + exceptionName);
810    }
811
812    /**
813     * Records the given exception using {@link #threadRecordFailure},
814     * then rethrows the exception, wrapping it in an
815     * AssertionFailedError if necessary.
816     */
817    public void threadUnexpectedException(Throwable t) {
818        threadRecordFailure(t);
819        t.printStackTrace();
820        if (t instanceof RuntimeException)
821            throw (RuntimeException) t;
822        else if (t instanceof Error)
823            throw (Error) t;
824        else {
825            AssertionFailedError afe =
826                new AssertionFailedError("unexpected exception: " + t);
827            afe.initCause(t);
828            throw afe;
829        }
830    }
831
832    /**
833     * Delays, via Thread.sleep, for the given millisecond delay, but
834     * if the sleep is shorter than specified, may re-sleep or yield
835     * until time elapses.  Ensures that the given time, as measured
836     * by System.nanoTime(), has elapsed.
837     */
838    static void delay(long millis) throws InterruptedException {
839        long nanos = millis * (1000 * 1000);
840        final long wakeupTime = System.nanoTime() + nanos;
841        do {
842            if (millis > 0L)
843                Thread.sleep(millis);
844            else // too short to sleep
845                Thread.yield();
846            nanos = wakeupTime - System.nanoTime();
847            millis = nanos / (1000 * 1000);
848        } while (nanos >= 0L);
849    }
850
851    /**
852     * Allows use of try-with-resources with per-test thread pools.
853     */
854    class PoolCleaner implements AutoCloseable {
855        private final ExecutorService pool;
856        public PoolCleaner(ExecutorService pool) { this.pool = pool; }
857        public void close() { joinPool(pool); }
858    }
859
860    /**
861     * An extension of PoolCleaner that has an action to release the pool.
862     */
863    class PoolCleanerWithReleaser extends PoolCleaner {
864        private final Runnable releaser;
865        public PoolCleanerWithReleaser(ExecutorService pool, Runnable releaser) {
866            super(pool);
867            this.releaser = releaser;
868        }
869        public void close() {
870            try {
871                releaser.run();
872            } finally {
873                super.close();
874            }
875        }
876    }
877
878    PoolCleaner cleaner(ExecutorService pool) {
879        return new PoolCleaner(pool);
880    }
881
882    PoolCleaner cleaner(ExecutorService pool, Runnable releaser) {
883        return new PoolCleanerWithReleaser(pool, releaser);
884    }
885
886    PoolCleaner cleaner(ExecutorService pool, CountDownLatch latch) {
887        return new PoolCleanerWithReleaser(pool, releaser(latch));
888    }
889
890    Runnable releaser(final CountDownLatch latch) {
891        return new Runnable() { public void run() {
892            do { latch.countDown(); }
893            while (latch.getCount() > 0);
894        }};
895    }
896
897    PoolCleaner cleaner(ExecutorService pool, AtomicBoolean flag) {
898        return new PoolCleanerWithReleaser(pool, releaser(flag));
899    }
900
901    Runnable releaser(final AtomicBoolean flag) {
902        return new Runnable() { public void run() { flag.set(true); }};
903    }
904
905    /**
906     * Waits out termination of a thread pool or fails doing so.
907     */
908    void joinPool(ExecutorService pool) {
909        try {
910            pool.shutdown();
911            if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS)) {
912                try {
913                    threadFail("ExecutorService " + pool +
914                               " did not terminate in a timely manner");
915                } finally {
916                    // last resort, for the benefit of subsequent tests
917                    pool.shutdownNow();
918                    pool.awaitTermination(MEDIUM_DELAY_MS, MILLISECONDS);
919                }
920            }
921        } catch (SecurityException ok) {
922            // Allowed in case test doesn't have privs
923        } catch (InterruptedException fail) {
924            threadFail("Unexpected InterruptedException");
925        }
926    }
927
928    /** Like Runnable, but with the freedom to throw anything */
929    interface Action { public void run() throws Throwable; }
930
931    /**
932     * Runs all the given actions in parallel, failing if any fail.
933     * Useful for running multiple variants of tests that are
934     * necessarily individually slow because they must block.
935     */
936    void testInParallel(Action ... actions) {
937        ExecutorService pool = Executors.newCachedThreadPool();
938        try (PoolCleaner cleaner = cleaner(pool)) {
939            ArrayList<Future<?>> futures = new ArrayList<>(actions.length);
940            for (final Action action : actions)
941                futures.add(pool.submit(new CheckedRunnable() {
942                    public void realRun() throws Throwable { action.run();}}));
943            for (Future<?> future : futures)
944                try {
945                    assertNull(future.get(LONG_DELAY_MS, MILLISECONDS));
946                } catch (ExecutionException ex) {
947                    threadUnexpectedException(ex.getCause());
948                } catch (Exception ex) {
949                    threadUnexpectedException(ex);
950                }
951        }
952    }
953
954    /**
955     * A debugging tool to print stack traces of most threads, as jstack does.
956     * Uninteresting threads are filtered out.
957     */
958    static void dumpTestThreads() {
959        // Android-change no ThreadMXBean
960        // ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
961        // System.err.println("------ stacktrace dump start ------");
962        // for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) {
963        //     String name = info.getThreadName();
964        //     if ("Signal Dispatcher".equals(name))
965        //         continue;
966        //     if ("Reference Handler".equals(name)
967        //         && info.getLockName().startsWith("java.lang.ref.Reference$Lock"))
968        //         continue;
969        //     if ("Finalizer".equals(name)
970        //         && info.getLockName().startsWith("java.lang.ref.ReferenceQueue$Lock"))
971        //         continue;
972        //     if ("checkForWedgedTest".equals(name))
973        //         continue;
974        //     System.err.print(info);
975        // }
976        // System.err.println("------ stacktrace dump end ------");
977    }
978
979    /**
980     * Checks that thread does not terminate within the default
981     * millisecond delay of {@code timeoutMillis()}.
982     */
983    void assertThreadStaysAlive(Thread thread) {
984        assertThreadStaysAlive(thread, timeoutMillis());
985    }
986
987    /**
988     * Checks that thread does not terminate within the given millisecond delay.
989     */
990    void assertThreadStaysAlive(Thread thread, long millis) {
991        try {
992            // No need to optimize the failing case via Thread.join.
993            delay(millis);
994            assertTrue(thread.isAlive());
995        } catch (InterruptedException fail) {
996            threadFail("Unexpected InterruptedException");
997        }
998    }
999
1000    /**
1001     * Checks that the threads do not terminate within the default
1002     * millisecond delay of {@code timeoutMillis()}.
1003     */
1004    void assertThreadsStayAlive(Thread... threads) {
1005        assertThreadsStayAlive(timeoutMillis(), threads);
1006    }
1007
1008    /**
1009     * Checks that the threads do not terminate within the given millisecond delay.
1010     */
1011    void assertThreadsStayAlive(long millis, Thread... threads) {
1012        try {
1013            // No need to optimize the failing case via Thread.join.
1014            delay(millis);
1015            for (Thread thread : threads)
1016                assertTrue(thread.isAlive());
1017        } catch (InterruptedException fail) {
1018            threadFail("Unexpected InterruptedException");
1019        }
1020    }
1021
1022    /**
1023     * Checks that future.get times out, with the default timeout of
1024     * {@code timeoutMillis()}.
1025     */
1026    void assertFutureTimesOut(Future future) {
1027        assertFutureTimesOut(future, timeoutMillis());
1028    }
1029
1030    /**
1031     * Checks that future.get times out, with the given millisecond timeout.
1032     */
1033    void assertFutureTimesOut(Future future, long timeoutMillis) {
1034        long startTime = System.nanoTime();
1035        try {
1036            future.get(timeoutMillis, MILLISECONDS);
1037            shouldThrow();
1038        } catch (TimeoutException success) {
1039        } catch (Exception fail) {
1040            threadUnexpectedException(fail);
1041        } finally { future.cancel(true); }
1042        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
1043    }
1044
1045    /**
1046     * Fails with message "should throw exception".
1047     */
1048    public void shouldThrow() {
1049        fail("Should throw exception");
1050    }
1051
1052    /**
1053     * Fails with message "should throw " + exceptionName.
1054     */
1055    public void shouldThrow(String exceptionName) {
1056        fail("Should throw " + exceptionName);
1057    }
1058
1059    /**
1060     * The number of elements to place in collections, arrays, etc.
1061     */
1062    public static final int SIZE = 20;
1063
1064    // Some convenient Integer constants
1065
1066    public static final Integer zero  = new Integer(0);
1067    public static final Integer one   = new Integer(1);
1068    public static final Integer two   = new Integer(2);
1069    public static final Integer three = new Integer(3);
1070    public static final Integer four  = new Integer(4);
1071    public static final Integer five  = new Integer(5);
1072    public static final Integer six   = new Integer(6);
1073    public static final Integer seven = new Integer(7);
1074    public static final Integer eight = new Integer(8);
1075    public static final Integer nine  = new Integer(9);
1076    public static final Integer m1  = new Integer(-1);
1077    public static final Integer m2  = new Integer(-2);
1078    public static final Integer m3  = new Integer(-3);
1079    public static final Integer m4  = new Integer(-4);
1080    public static final Integer m5  = new Integer(-5);
1081    public static final Integer m6  = new Integer(-6);
1082    public static final Integer m10 = new Integer(-10);
1083
1084    /**
1085     * Runs Runnable r with a security policy that permits precisely
1086     * the specified permissions.  If there is no current security
1087     * manager, the runnable is run twice, both with and without a
1088     * security manager.  We require that any security manager permit
1089     * getPolicy/setPolicy.
1090     */
1091    public void runWithPermissions(Runnable r, Permission... permissions) {
1092        // Android-changed - no SecurityManager
1093        // SecurityManager sm = System.getSecurityManager();
1094        // if (sm == null) {
1095        //     r.run();
1096        // }
1097        // runWithSecurityManagerWithPermissions(r, permissions);
1098        r.run();
1099    }
1100
1101    /**
1102     * Runs Runnable r with a security policy that permits precisely
1103     * the specified permissions.  If there is no current security
1104     * manager, a temporary one is set for the duration of the
1105     * Runnable.  We require that any security manager permit
1106     * getPolicy/setPolicy.
1107     */
1108    public void runWithSecurityManagerWithPermissions(Runnable r,
1109                                                      Permission... permissions) {
1110        // Android-changed - no SecurityManager
1111        // SecurityManager sm = System.getSecurityManager();
1112        // if (sm == null) {
1113        //     Policy savedPolicy = Policy.getPolicy();
1114        //     try {
1115        //         Policy.setPolicy(permissivePolicy());
1116        //         System.setSecurityManager(new SecurityManager());
1117        //         runWithSecurityManagerWithPermissions(r, permissions);
1118        //     } finally {
1119        //         System.setSecurityManager(null);
1120        //         Policy.setPolicy(savedPolicy);
1121        //     }
1122        // } else {
1123        //     Policy savedPolicy = Policy.getPolicy();
1124        //     AdjustablePolicy policy = new AdjustablePolicy(permissions);
1125        //     Policy.setPolicy(policy);
1126
1127        //     try {
1128        //         r.run();
1129        //     } finally {
1130        //         policy.addPermission(new SecurityPermission("setPolicy"));
1131        //         Policy.setPolicy(savedPolicy);
1132        //     }
1133        // }
1134        r.run();
1135    }
1136
1137    /**
1138     * Runs a runnable without any permissions.
1139     */
1140    public void runWithoutPermissions(Runnable r) {
1141        runWithPermissions(r);
1142    }
1143
1144    /**
1145     * A security policy where new permissions can be dynamically added
1146     * or all cleared.
1147     */
1148    public static class AdjustablePolicy extends java.security.Policy {
1149        Permissions perms = new Permissions();
1150        AdjustablePolicy(Permission... permissions) {
1151            for (Permission permission : permissions)
1152                perms.add(permission);
1153        }
1154        void addPermission(Permission perm) { perms.add(perm); }
1155        void clearPermissions() { perms = new Permissions(); }
1156        public PermissionCollection getPermissions(CodeSource cs) {
1157            return perms;
1158        }
1159        public PermissionCollection getPermissions(ProtectionDomain pd) {
1160            return perms;
1161        }
1162        public boolean implies(ProtectionDomain pd, Permission p) {
1163            return perms.implies(p);
1164        }
1165        public void refresh() {}
1166        public String toString() {
1167            List<Permission> ps = new ArrayList<Permission>();
1168            for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
1169                ps.add(e.nextElement());
1170            return "AdjustablePolicy with permissions " + ps;
1171        }
1172    }
1173
1174    /**
1175     * Returns a policy containing all the permissions we ever need.
1176     */
1177    public static Policy permissivePolicy() {
1178        return new AdjustablePolicy
1179            // Permissions j.u.c. needs directly
1180            (new RuntimePermission("modifyThread"),
1181             new RuntimePermission("getClassLoader"),
1182             new RuntimePermission("setContextClassLoader"),
1183             // Permissions needed to change permissions!
1184             new SecurityPermission("getPolicy"),
1185             new SecurityPermission("setPolicy"),
1186             new RuntimePermission("setSecurityManager"),
1187             // Permissions needed by the junit test harness
1188             new RuntimePermission("accessDeclaredMembers"),
1189             new PropertyPermission("*", "read"),
1190             new java.io.FilePermission("<<ALL FILES>>", "read"));
1191    }
1192
1193    /**
1194     * Sleeps until the given time has elapsed.
1195     * Throws AssertionFailedError if interrupted.
1196     */
1197    void sleep(long millis) {
1198        try {
1199            delay(millis);
1200        } catch (InterruptedException fail) {
1201            AssertionFailedError afe =
1202                new AssertionFailedError("Unexpected InterruptedException");
1203            afe.initCause(fail);
1204            throw afe;
1205        }
1206    }
1207
1208    /**
1209     * Spin-waits up to the specified number of milliseconds for the given
1210     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1211     */
1212    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
1213        long startTime = System.nanoTime();
1214        for (;;) {
1215            Thread.State s = thread.getState();
1216            if (s == Thread.State.BLOCKED ||
1217                s == Thread.State.WAITING ||
1218                s == Thread.State.TIMED_WAITING)
1219                return;
1220            else if (s == Thread.State.TERMINATED)
1221                fail("Unexpected thread termination");
1222            else if (millisElapsedSince(startTime) > timeoutMillis) {
1223                threadAssertTrue(thread.isAlive());
1224                return;
1225            }
1226            Thread.yield();
1227        }
1228    }
1229
1230    /**
1231     * Waits up to LONG_DELAY_MS for the given thread to enter a wait
1232     * state: BLOCKED, WAITING, or TIMED_WAITING.
1233     */
1234    void waitForThreadToEnterWaitState(Thread thread) {
1235        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
1236    }
1237
1238    /**
1239     * Returns the number of milliseconds since time given by
1240     * startNanoTime, which must have been previously returned from a
1241     * call to {@link System#nanoTime()}.
1242     */
1243    static long millisElapsedSince(long startNanoTime) {
1244        return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
1245    }
1246
1247//     void assertTerminatesPromptly(long timeoutMillis, Runnable r) {
1248//         long startTime = System.nanoTime();
1249//         try {
1250//             r.run();
1251//         } catch (Throwable fail) { threadUnexpectedException(fail); }
1252//         if (millisElapsedSince(startTime) > timeoutMillis/2)
1253//             throw new AssertionFailedError("did not return promptly");
1254//     }
1255
1256//     void assertTerminatesPromptly(Runnable r) {
1257//         assertTerminatesPromptly(LONG_DELAY_MS/2, r);
1258//     }
1259
1260    /**
1261     * Checks that timed f.get() returns the expected value, and does not
1262     * wait for the timeout to elapse before returning.
1263     */
1264    <T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) {
1265        long startTime = System.nanoTime();
1266        try {
1267            assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
1268        } catch (Throwable fail) { threadUnexpectedException(fail); }
1269        if (millisElapsedSince(startTime) > timeoutMillis/2)
1270            throw new AssertionFailedError("timed get did not return promptly");
1271    }
1272
1273    <T> void checkTimedGet(Future<T> f, T expectedValue) {
1274        checkTimedGet(f, expectedValue, LONG_DELAY_MS);
1275    }
1276
1277    /**
1278     * Returns a new started daemon Thread running the given runnable.
1279     */
1280    Thread newStartedThread(Runnable runnable) {
1281        Thread t = new Thread(runnable);
1282        t.setDaemon(true);
1283        t.start();
1284        return t;
1285    }
1286
1287    /**
1288     * Waits for the specified time (in milliseconds) for the thread
1289     * to terminate (using {@link Thread#join(long)}), else interrupts
1290     * the thread (in the hope that it may terminate later) and fails.
1291     */
1292    void awaitTermination(Thread t, long timeoutMillis) {
1293        try {
1294            t.join(timeoutMillis);
1295        } catch (InterruptedException fail) {
1296            threadUnexpectedException(fail);
1297        } finally {
1298            if (t.getState() != Thread.State.TERMINATED) {
1299                t.interrupt();
1300                threadFail("timed out waiting for thread to terminate");
1301            }
1302        }
1303    }
1304
1305    /**
1306     * Waits for LONG_DELAY_MS milliseconds for the thread to
1307     * terminate (using {@link Thread#join(long)}), else interrupts
1308     * the thread (in the hope that it may terminate later) and fails.
1309     */
1310    void awaitTermination(Thread t) {
1311        awaitTermination(t, LONG_DELAY_MS);
1312    }
1313
1314    // Some convenient Runnable classes
1315
1316    public abstract class CheckedRunnable implements Runnable {
1317        protected abstract void realRun() throws Throwable;
1318
1319        public final void run() {
1320            try {
1321                realRun();
1322            } catch (Throwable fail) {
1323                threadUnexpectedException(fail);
1324            }
1325        }
1326    }
1327
1328    public abstract class RunnableShouldThrow implements Runnable {
1329        protected abstract void realRun() throws Throwable;
1330
1331        final Class<?> exceptionClass;
1332
1333        <T extends Throwable> RunnableShouldThrow(Class<T> exceptionClass) {
1334            this.exceptionClass = exceptionClass;
1335        }
1336
1337        public final void run() {
1338            try {
1339                realRun();
1340                threadShouldThrow(exceptionClass.getSimpleName());
1341            } catch (Throwable t) {
1342                if (! exceptionClass.isInstance(t))
1343                    threadUnexpectedException(t);
1344            }
1345        }
1346    }
1347
1348    public abstract class ThreadShouldThrow extends Thread {
1349        protected abstract void realRun() throws Throwable;
1350
1351        final Class<?> exceptionClass;
1352
1353        <T extends Throwable> ThreadShouldThrow(Class<T> exceptionClass) {
1354            this.exceptionClass = exceptionClass;
1355        }
1356
1357        public final void run() {
1358            try {
1359                realRun();
1360                threadShouldThrow(exceptionClass.getSimpleName());
1361            } catch (Throwable t) {
1362                if (! exceptionClass.isInstance(t))
1363                    threadUnexpectedException(t);
1364            }
1365        }
1366    }
1367
1368    public abstract class CheckedInterruptedRunnable implements Runnable {
1369        protected abstract void realRun() throws Throwable;
1370
1371        public final void run() {
1372            try {
1373                realRun();
1374                threadShouldThrow("InterruptedException");
1375            } catch (InterruptedException success) {
1376                threadAssertFalse(Thread.interrupted());
1377            } catch (Throwable fail) {
1378                threadUnexpectedException(fail);
1379            }
1380        }
1381    }
1382
1383    public abstract class CheckedCallable<T> implements Callable<T> {
1384        protected abstract T realCall() throws Throwable;
1385
1386        public final T call() {
1387            try {
1388                return realCall();
1389            } catch (Throwable fail) {
1390                threadUnexpectedException(fail);
1391                return null;
1392            }
1393        }
1394    }
1395
1396    public abstract class CheckedInterruptedCallable<T>
1397        implements Callable<T> {
1398        protected abstract T realCall() throws Throwable;
1399
1400        public final T call() {
1401            try {
1402                T result = realCall();
1403                threadShouldThrow("InterruptedException");
1404                return result;
1405            } catch (InterruptedException success) {
1406                threadAssertFalse(Thread.interrupted());
1407            } catch (Throwable fail) {
1408                threadUnexpectedException(fail);
1409            }
1410            return null;
1411        }
1412    }
1413
1414    public static class NoOpRunnable implements Runnable {
1415        public void run() {}
1416    }
1417
1418    public static class NoOpCallable implements Callable {
1419        public Object call() { return Boolean.TRUE; }
1420    }
1421
1422    public static final String TEST_STRING = "a test string";
1423
1424    public static class StringTask implements Callable<String> {
1425        final String value;
1426        public StringTask() { this(TEST_STRING); }
1427        public StringTask(String value) { this.value = value; }
1428        public String call() { return value; }
1429    }
1430
1431    public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
1432        return new CheckedCallable<String>() {
1433            protected String realCall() {
1434                try {
1435                    latch.await();
1436                } catch (InterruptedException quittingTime) {}
1437                return TEST_STRING;
1438            }};
1439    }
1440
1441    public Runnable countDowner(final CountDownLatch latch) {
1442        return new CheckedRunnable() {
1443            public void realRun() throws InterruptedException {
1444                latch.countDown();
1445            }};
1446    }
1447
1448    class LatchAwaiter extends CheckedRunnable {
1449        static final int NEW = 0;
1450        static final int RUNNING = 1;
1451        static final int DONE = 2;
1452        final CountDownLatch latch;
1453        int state = NEW;
1454        LatchAwaiter(CountDownLatch latch) { this.latch = latch; }
1455        public void realRun() throws InterruptedException {
1456            state = 1;
1457            await(latch);
1458            state = 2;
1459        }
1460    }
1461
1462    public LatchAwaiter awaiter(CountDownLatch latch) {
1463        return new LatchAwaiter(latch);
1464    }
1465
1466    public void await(CountDownLatch latch, long timeoutMillis) {
1467        try {
1468            if (!latch.await(timeoutMillis, MILLISECONDS))
1469                fail("timed out waiting for CountDownLatch for "
1470                     + (timeoutMillis/1000) + " sec");
1471        } catch (Throwable fail) {
1472            threadUnexpectedException(fail);
1473        }
1474    }
1475
1476    public void await(CountDownLatch latch) {
1477        await(latch, LONG_DELAY_MS);
1478    }
1479
1480    public void await(Semaphore semaphore) {
1481        try {
1482            if (!semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS))
1483                fail("timed out waiting for Semaphore for "
1484                     + (LONG_DELAY_MS/1000) + " sec");
1485        } catch (Throwable fail) {
1486            threadUnexpectedException(fail);
1487        }
1488    }
1489
1490//     /**
1491//      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1492//      */
1493//     public void await(AtomicBoolean flag) {
1494//         await(flag, LONG_DELAY_MS);
1495//     }
1496
1497//     /**
1498//      * Spin-waits up to the specified timeout until flag becomes true.
1499//      */
1500//     public void await(AtomicBoolean flag, long timeoutMillis) {
1501//         long startTime = System.nanoTime();
1502//         while (!flag.get()) {
1503//             if (millisElapsedSince(startTime) > timeoutMillis)
1504//                 throw new AssertionFailedError("timed out");
1505//             Thread.yield();
1506//         }
1507//     }
1508
1509    public static class NPETask implements Callable<String> {
1510        public String call() { throw new NullPointerException(); }
1511    }
1512
1513    public static class CallableOne implements Callable<Integer> {
1514        public Integer call() { return one; }
1515    }
1516
1517    public class ShortRunnable extends CheckedRunnable {
1518        protected void realRun() throws Throwable {
1519            delay(SHORT_DELAY_MS);
1520        }
1521    }
1522
1523    public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1524        protected void realRun() throws InterruptedException {
1525            delay(SHORT_DELAY_MS);
1526        }
1527    }
1528
1529    public class SmallRunnable extends CheckedRunnable {
1530        protected void realRun() throws Throwable {
1531            delay(SMALL_DELAY_MS);
1532        }
1533    }
1534
1535    public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1536        protected void realRun() {
1537            try {
1538                delay(SMALL_DELAY_MS);
1539            } catch (InterruptedException ok) {}
1540        }
1541    }
1542
1543    public class SmallCallable extends CheckedCallable {
1544        protected Object realCall() throws InterruptedException {
1545            delay(SMALL_DELAY_MS);
1546            return Boolean.TRUE;
1547        }
1548    }
1549
1550    public class MediumRunnable extends CheckedRunnable {
1551        protected void realRun() throws Throwable {
1552            delay(MEDIUM_DELAY_MS);
1553        }
1554    }
1555
1556    public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1557        protected void realRun() throws InterruptedException {
1558            delay(MEDIUM_DELAY_MS);
1559        }
1560    }
1561
1562    public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1563        return new CheckedRunnable() {
1564            protected void realRun() {
1565                try {
1566                    delay(timeoutMillis);
1567                } catch (InterruptedException ok) {}
1568            }};
1569    }
1570
1571    public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1572        protected void realRun() {
1573            try {
1574                delay(MEDIUM_DELAY_MS);
1575            } catch (InterruptedException ok) {}
1576        }
1577    }
1578
1579    public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1580        protected void realRun() {
1581            try {
1582                delay(LONG_DELAY_MS);
1583            } catch (InterruptedException ok) {}
1584        }
1585    }
1586
1587    /**
1588     * For use as ThreadFactory in constructors
1589     */
1590    public static class SimpleThreadFactory implements ThreadFactory {
1591        public Thread newThread(Runnable r) {
1592            return new Thread(r);
1593        }
1594    }
1595
1596    public interface TrackedRunnable extends Runnable {
1597        boolean isDone();
1598    }
1599
1600    public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
1601        return new TrackedRunnable() {
1602                private volatile boolean done = false;
1603                public boolean isDone() { return done; }
1604                public void run() {
1605                    try {
1606                        delay(timeoutMillis);
1607                        done = true;
1608                    } catch (InterruptedException ok) {}
1609                }
1610            };
1611    }
1612
1613    public static class TrackedShortRunnable implements Runnable {
1614        public volatile boolean done = false;
1615        public void run() {
1616            try {
1617                delay(SHORT_DELAY_MS);
1618                done = true;
1619            } catch (InterruptedException ok) {}
1620        }
1621    }
1622
1623    public static class TrackedSmallRunnable implements Runnable {
1624        public volatile boolean done = false;
1625        public void run() {
1626            try {
1627                delay(SMALL_DELAY_MS);
1628                done = true;
1629            } catch (InterruptedException ok) {}
1630        }
1631    }
1632
1633    public static class TrackedMediumRunnable implements Runnable {
1634        public volatile boolean done = false;
1635        public void run() {
1636            try {
1637                delay(MEDIUM_DELAY_MS);
1638                done = true;
1639            } catch (InterruptedException ok) {}
1640        }
1641    }
1642
1643    public static class TrackedLongRunnable implements Runnable {
1644        public volatile boolean done = false;
1645        public void run() {
1646            try {
1647                delay(LONG_DELAY_MS);
1648                done = true;
1649            } catch (InterruptedException ok) {}
1650        }
1651    }
1652
1653    public static class TrackedNoOpRunnable implements Runnable {
1654        public volatile boolean done = false;
1655        public void run() {
1656            done = true;
1657        }
1658    }
1659
1660    public static class TrackedCallable implements Callable {
1661        public volatile boolean done = false;
1662        public Object call() {
1663            try {
1664                delay(SMALL_DELAY_MS);
1665                done = true;
1666            } catch (InterruptedException ok) {}
1667            return Boolean.TRUE;
1668        }
1669    }
1670
1671    /**
1672     * Analog of CheckedRunnable for RecursiveAction
1673     */
1674    public abstract class CheckedRecursiveAction extends RecursiveAction {
1675        protected abstract void realCompute() throws Throwable;
1676
1677        @Override protected final void compute() {
1678            try {
1679                realCompute();
1680            } catch (Throwable fail) {
1681                threadUnexpectedException(fail);
1682            }
1683        }
1684    }
1685
1686    /**
1687     * Analog of CheckedCallable for RecursiveTask
1688     */
1689    public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1690        protected abstract T realCompute() throws Throwable;
1691
1692        @Override protected final T compute() {
1693            try {
1694                return realCompute();
1695            } catch (Throwable fail) {
1696                threadUnexpectedException(fail);
1697                return null;
1698            }
1699        }
1700    }
1701
1702    /**
1703     * For use as RejectedExecutionHandler in constructors
1704     */
1705    public static class NoOpREHandler implements RejectedExecutionHandler {
1706        public void rejectedExecution(Runnable r,
1707                                      ThreadPoolExecutor executor) {}
1708    }
1709
1710    /**
1711     * A CyclicBarrier that uses timed await and fails with
1712     * AssertionFailedErrors instead of throwing checked exceptions.
1713     */
1714    public class CheckedBarrier extends CyclicBarrier {
1715        public CheckedBarrier(int parties) { super(parties); }
1716
1717        public int await() {
1718            try {
1719                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1720            } catch (TimeoutException timedOut) {
1721                throw new AssertionFailedError("timed out");
1722            } catch (Exception fail) {
1723                AssertionFailedError afe =
1724                    new AssertionFailedError("Unexpected exception: " + fail);
1725                afe.initCause(fail);
1726                throw afe;
1727            }
1728        }
1729    }
1730
1731    void checkEmpty(BlockingQueue q) {
1732        try {
1733            assertTrue(q.isEmpty());
1734            assertEquals(0, q.size());
1735            assertNull(q.peek());
1736            assertNull(q.poll());
1737            assertNull(q.poll(0, MILLISECONDS));
1738            assertEquals(q.toString(), "[]");
1739            assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1740            assertFalse(q.iterator().hasNext());
1741            try {
1742                q.element();
1743                shouldThrow();
1744            } catch (NoSuchElementException success) {}
1745            try {
1746                q.iterator().next();
1747                shouldThrow();
1748            } catch (NoSuchElementException success) {}
1749            try {
1750                q.remove();
1751                shouldThrow();
1752            } catch (NoSuchElementException success) {}
1753        } catch (InterruptedException fail) { threadUnexpectedException(fail); }
1754    }
1755
1756    void assertSerialEquals(Object x, Object y) {
1757        assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1758    }
1759
1760    void assertNotSerialEquals(Object x, Object y) {
1761        assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1762    }
1763
1764    byte[] serialBytes(Object o) {
1765        try {
1766            ByteArrayOutputStream bos = new ByteArrayOutputStream();
1767            ObjectOutputStream oos = new ObjectOutputStream(bos);
1768            oos.writeObject(o);
1769            oos.flush();
1770            oos.close();
1771            return bos.toByteArray();
1772        } catch (Throwable fail) {
1773            threadUnexpectedException(fail);
1774            return new byte[0];
1775        }
1776    }
1777
1778    @SuppressWarnings("unchecked")
1779    <T> T serialClone(T o) {
1780        try {
1781            ObjectInputStream ois = new ObjectInputStream
1782                (new ByteArrayInputStream(serialBytes(o)));
1783            T clone = (T) ois.readObject();
1784            assertSame(o.getClass(), clone.getClass());
1785            return clone;
1786        } catch (Throwable fail) {
1787            threadUnexpectedException(fail);
1788            return null;
1789        }
1790    }
1791
1792    public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1793                             Runnable... throwingActions) {
1794        for (Runnable throwingAction : throwingActions) {
1795            boolean threw = false;
1796            try { throwingAction.run(); }
1797            catch (Throwable t) {
1798                threw = true;
1799                if (!expectedExceptionClass.isInstance(t)) {
1800                    AssertionFailedError afe =
1801                        new AssertionFailedError
1802                        ("Expected " + expectedExceptionClass.getName() +
1803                         ", got " + t.getClass().getName());
1804                    afe.initCause(t);
1805                    threadUnexpectedException(afe);
1806                }
1807            }
1808            if (!threw)
1809                shouldThrow(expectedExceptionClass.getName());
1810        }
1811    }
1812
1813    public void assertIteratorExhausted(Iterator<?> it) {
1814        try {
1815            it.next();
1816            shouldThrow();
1817        } catch (NoSuchElementException success) {}
1818        assertFalse(it.hasNext());
1819    }
1820}
1821