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/*
10 * Source:
11 * http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/test/tck/JSR166TestCase.java?revision=1.90
12 * (We have made some trivial local modifications (commented out
13 * uncompilable code).)
14 */
15
16package com.google.common.util.concurrent;
17
18import junit.framework.*;
19import java.io.ByteArrayInputStream;
20import java.io.ByteArrayOutputStream;
21import java.io.ObjectInputStream;
22import java.io.ObjectOutputStream;
23import java.util.Arrays;
24import java.util.Date;
25import java.util.NoSuchElementException;
26import java.util.PropertyPermission;
27import java.util.concurrent.*;
28import java.util.concurrent.atomic.AtomicBoolean;
29import java.util.concurrent.atomic.AtomicReference;
30import static java.util.concurrent.TimeUnit.MILLISECONDS;
31import static java.util.concurrent.TimeUnit.NANOSECONDS;
32import java.security.CodeSource;
33import java.security.Permission;
34import java.security.PermissionCollection;
35import java.security.Permissions;
36import java.security.Policy;
37import java.security.ProtectionDomain;
38import java.security.SecurityPermission;
39
40/**
41 * Base class for JSR166 Junit TCK tests.  Defines some constants,
42 * utility methods and classes, as well as a simple framework for
43 * helping to make sure that assertions failing in generated threads
44 * cause the associated test that generated them to itself fail (which
45 * JUnit does not otherwise arrange).  The rules for creating such
46 * tests are:
47 *
48 * <ol>
49 *
50 * <li> All assertions in code running in generated threads must use
51 * the forms {@link #threadFail}, {@link #threadAssertTrue}, {@link
52 * #threadAssertEquals}, or {@link #threadAssertNull}, (not
53 * {@code fail}, {@code assertTrue}, etc.) It is OK (but not
54 * particularly recommended) for other code to use these forms too.
55 * Only the most typically used JUnit assertion methods are defined
56 * this way, but enough to live with.</li>
57 *
58 * <li> If you override {@link #setUp} or {@link #tearDown}, make sure
59 * to invoke {@code super.setUp} and {@code super.tearDown} within
60 * them. These methods are used to clear and check for thread
61 * assertion failures.</li>
62 *
63 * <li>All delays and timeouts must use one of the constants {@code
64 * SHORT_DELAY_MS}, {@code SMALL_DELAY_MS}, {@code MEDIUM_DELAY_MS},
65 * {@code LONG_DELAY_MS}. The idea here is that a SHORT is always
66 * discriminable from zero time, and always allows enough time for the
67 * small amounts of computation (creating a thread, calling a few
68 * methods, etc) needed to reach a timeout point. Similarly, a SMALL
69 * is always discriminable as larger than SHORT and smaller than
70 * MEDIUM.  And so on. These constants are set to conservative values,
71 * but even so, if there is ever any doubt, they can all be increased
72 * in one spot to rerun tests on slower platforms.</li>
73 *
74 * <li> All threads generated must be joined inside each test case
75 * method (or {@code fail} to do so) before returning from the
76 * method. The {@code joinPool} method can be used to do this when
77 * using Executors.</li>
78 *
79 * </ol>
80 *
81 * <p> <b>Other notes</b>
82 * <ul>
83 *
84 * <li> Usually, there is one testcase method per JSR166 method
85 * covering "normal" operation, and then as many exception-testing
86 * methods as there are exceptions the method can throw. Sometimes
87 * there are multiple tests per JSR166 method when the different
88 * "normal" behaviors differ significantly. And sometimes testcases
89 * cover multiple methods when they cannot be tested in
90 * isolation.</li>
91 *
92 * <li> The documentation style for testcases is to provide as javadoc
93 * a simple sentence or two describing the property that the testcase
94 * method purports to test. The javadocs do not say anything about how
95 * the property is tested. To find out, read the code.</li>
96 *
97 * <li> These tests are "conformance tests", and do not attempt to
98 * test throughput, latency, scalability or other performance factors
99 * (see the separate "jtreg" tests for a set intended to check these
100 * for the most central aspects of functionality.) So, most tests use
101 * the smallest sensible numbers of threads, collection sizes, etc
102 * needed to check basic conformance.</li>
103 *
104 * <li>The test classes currently do not declare inclusion in
105 * any particular package to simplify things for people integrating
106 * them in TCK test suites.</li>
107 *
108 * <li> As a convenience, the {@code main} of this class (JSR166TestCase)
109 * runs all JSR166 unit tests.</li>
110 *
111 * </ul>
112 */
113abstract class JSR166TestCase extends TestCase {
114    private static final boolean useSecurityManager =
115        Boolean.getBoolean("jsr166.useSecurityManager");
116
117    protected static final boolean expensiveTests =
118        Boolean.getBoolean("jsr166.expensiveTests");
119
120    /**
121     * If true, report on stdout all "slow" tests, that is, ones that
122     * take more than profileThreshold milliseconds to execute.
123     */
124    private static final boolean profileTests =
125        Boolean.getBoolean("jsr166.profileTests");
126
127    /**
128     * The number of milliseconds that tests are permitted for
129     * execution without being reported, when profileTests is set.
130     */
131    private static final long profileThreshold =
132        Long.getLong("jsr166.profileThreshold", 100);
133
134    protected void runTest() throws Throwable {
135        if (profileTests)
136            runTestProfiled();
137        else
138            super.runTest();
139    }
140
141    protected void runTestProfiled() throws Throwable {
142        long t0 = System.nanoTime();
143        try {
144            super.runTest();
145        } finally {
146            long elapsedMillis =
147                (System.nanoTime() - t0) / (1000L * 1000L);
148            if (elapsedMillis >= profileThreshold)
149                System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
150        }
151    }
152
153//     /**
154//      * Runs all JSR166 unit tests using junit.textui.TestRunner
155//      */
156//     public static void main(String[] args) {
157//         if (useSecurityManager) {
158//             System.err.println("Setting a permissive security manager");
159//             Policy.setPolicy(permissivePolicy());
160//             System.setSecurityManager(new SecurityManager());
161//         }
162//         int iters = (args.length == 0) ? 1 : Integer.parseInt(args[0]);
163
164//         Test s = suite();
165//         for (int i = 0; i < iters; ++i) {
166//             junit.textui.TestRunner.run(s);
167//             System.gc();
168//             System.runFinalization();
169//         }
170//         System.exit(0);
171//     }
172
173//     public static TestSuite newTestSuite(Object... suiteOrClasses) {
174//         TestSuite suite = new TestSuite();
175//         for (Object suiteOrClass : suiteOrClasses) {
176//             if (suiteOrClass instanceof TestSuite)
177//                 suite.addTest((TestSuite) suiteOrClass);
178//             else if (suiteOrClass instanceof Class)
179//                 suite.addTest(new TestSuite((Class<?>) suiteOrClass));
180//             else
181//                 throw new ClassCastException("not a test suite or class");
182//         }
183//         return suite;
184//     }
185
186//     /**
187//      * Collects all JSR166 unit tests as one suite.
188//      */
189//     public static Test suite() {
190//         return newTestSuite(
191//             ForkJoinPoolTest.suite(),
192//             ForkJoinTaskTest.suite(),
193//             RecursiveActionTest.suite(),
194//             RecursiveTaskTest.suite(),
195//             LinkedTransferQueueTest.suite(),
196//             PhaserTest.suite(),
197//             ThreadLocalRandomTest.suite(),
198//             AbstractExecutorServiceTest.suite(),
199//             AbstractQueueTest.suite(),
200//             AbstractQueuedSynchronizerTest.suite(),
201//             AbstractQueuedLongSynchronizerTest.suite(),
202//             ArrayBlockingQueueTest.suite(),
203//             ArrayDequeTest.suite(),
204//             AtomicBooleanTest.suite(),
205//             AtomicIntegerArrayTest.suite(),
206//             AtomicIntegerFieldUpdaterTest.suite(),
207//             AtomicIntegerTest.suite(),
208//             AtomicLongArrayTest.suite(),
209//             AtomicLongFieldUpdaterTest.suite(),
210//             AtomicLongTest.suite(),
211//             AtomicMarkableReferenceTest.suite(),
212//             AtomicReferenceArrayTest.suite(),
213//             AtomicReferenceFieldUpdaterTest.suite(),
214//             AtomicReferenceTest.suite(),
215//             AtomicStampedReferenceTest.suite(),
216//             ConcurrentHashMapTest.suite(),
217//             ConcurrentLinkedDequeTest.suite(),
218//             ConcurrentLinkedQueueTest.suite(),
219//             ConcurrentSkipListMapTest.suite(),
220//             ConcurrentSkipListSubMapTest.suite(),
221//             ConcurrentSkipListSetTest.suite(),
222//             ConcurrentSkipListSubSetTest.suite(),
223//             CopyOnWriteArrayListTest.suite(),
224//             CopyOnWriteArraySetTest.suite(),
225//             CountDownLatchTest.suite(),
226//             CyclicBarrierTest.suite(),
227//             DelayQueueTest.suite(),
228//             EntryTest.suite(),
229//             ExchangerTest.suite(),
230//             ExecutorsTest.suite(),
231//             ExecutorCompletionServiceTest.suite(),
232//             FutureTaskTest.suite(),
233//             LinkedBlockingDequeTest.suite(),
234//             LinkedBlockingQueueTest.suite(),
235//             LinkedListTest.suite(),
236//             LockSupportTest.suite(),
237//             PriorityBlockingQueueTest.suite(),
238//             PriorityQueueTest.suite(),
239//             ReentrantLockTest.suite(),
240//             ReentrantReadWriteLockTest.suite(),
241//             ScheduledExecutorTest.suite(),
242//             ScheduledExecutorSubclassTest.suite(),
243//             SemaphoreTest.suite(),
244//             SynchronousQueueTest.suite(),
245//             SystemTest.suite(),
246//             ThreadLocalTest.suite(),
247//             ThreadPoolExecutorTest.suite(),
248//             ThreadPoolExecutorSubclassTest.suite(),
249//             ThreadTest.suite(),
250//             TimeUnitTest.suite(),
251//             TreeMapTest.suite(),
252//             TreeSetTest.suite(),
253//             TreeSubMapTest.suite(),
254//             TreeSubSetTest.suite());
255//     }
256
257    public static long SHORT_DELAY_MS;
258    public static long SMALL_DELAY_MS;
259    public static long MEDIUM_DELAY_MS;
260    public static long LONG_DELAY_MS;
261
262    /**
263     * Returns the shortest timed delay. This could
264     * be reimplemented to use for example a Property.
265     */
266    protected long getShortDelay() {
267        return 50;
268    }
269
270    /**
271     * Sets delays as multiples of SHORT_DELAY.
272     */
273    protected void setDelays() {
274        SHORT_DELAY_MS = getShortDelay();
275        SMALL_DELAY_MS  = SHORT_DELAY_MS * 5;
276        MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
277        LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
278    }
279
280    /**
281     * Returns a timeout in milliseconds to be used in tests that
282     * verify that operations block or time out.
283     */
284    long timeoutMillis() {
285        return SHORT_DELAY_MS / 4;
286    }
287
288    /**
289     * Returns a new Date instance representing a time delayMillis
290     * milliseconds in the future.
291     */
292    Date delayedDate(long delayMillis) {
293        return new Date(System.currentTimeMillis() + delayMillis);
294    }
295
296    /**
297     * The first exception encountered if any threadAssertXXX method fails.
298     */
299    private final AtomicReference<Throwable> threadFailure
300        = new AtomicReference<Throwable>(null);
301
302    /**
303     * Records an exception so that it can be rethrown later in the test
304     * harness thread, triggering a test case failure.  Only the first
305     * failure is recorded; subsequent calls to this method from within
306     * the same test have no effect.
307     */
308    public void threadRecordFailure(Throwable t) {
309        threadFailure.compareAndSet(null, t);
310    }
311
312    public void setUp() {
313        setDelays();
314    }
315
316    /**
317     * Extra checks that get done for all test cases.
318     *
319     * Triggers test case failure if any thread assertions have failed,
320     * by rethrowing, in the test harness thread, any exception recorded
321     * earlier by threadRecordFailure.
322     *
323     * Triggers test case failure if interrupt status is set in the main thread.
324     */
325    public void tearDown() throws Exception {
326        Throwable t = threadFailure.getAndSet(null);
327        if (t != null) {
328            if (t instanceof Error)
329                throw (Error) t;
330            else if (t instanceof RuntimeException)
331                throw (RuntimeException) t;
332            else if (t instanceof Exception)
333                throw (Exception) t;
334            else {
335                AssertionFailedError afe =
336                    new AssertionFailedError(t.toString());
337                afe.initCause(t);
338                throw afe;
339            }
340        }
341
342        if (Thread.interrupted())
343            throw new AssertionFailedError("interrupt status set in main thread");
344    }
345
346    /**
347     * Just like fail(reason), but additionally recording (using
348     * threadRecordFailure) any AssertionFailedError thrown, so that
349     * the current testcase will fail.
350     */
351    public void threadFail(String reason) {
352        try {
353            fail(reason);
354        } catch (AssertionFailedError t) {
355            threadRecordFailure(t);
356            fail(reason);
357        }
358    }
359
360    /**
361     * Just like assertTrue(b), but additionally recording (using
362     * threadRecordFailure) any AssertionFailedError thrown, so that
363     * the current testcase will fail.
364     */
365    public void threadAssertTrue(boolean b) {
366        try {
367            assertTrue(b);
368        } catch (AssertionFailedError t) {
369            threadRecordFailure(t);
370            throw t;
371        }
372    }
373
374    /**
375     * Just like assertFalse(b), but additionally recording (using
376     * threadRecordFailure) any AssertionFailedError thrown, so that
377     * the current testcase will fail.
378     */
379    public void threadAssertFalse(boolean b) {
380        try {
381            assertFalse(b);
382        } catch (AssertionFailedError t) {
383            threadRecordFailure(t);
384            throw t;
385        }
386    }
387
388    /**
389     * Just like assertNull(x), but additionally recording (using
390     * threadRecordFailure) any AssertionFailedError thrown, so that
391     * the current testcase will fail.
392     */
393    public void threadAssertNull(Object x) {
394        try {
395            assertNull(x);
396        } catch (AssertionFailedError t) {
397            threadRecordFailure(t);
398            throw t;
399        }
400    }
401
402    /**
403     * Just like assertEquals(x, y), but additionally recording (using
404     * threadRecordFailure) any AssertionFailedError thrown, so that
405     * the current testcase will fail.
406     */
407    public void threadAssertEquals(long x, long y) {
408        try {
409            assertEquals(x, y);
410        } catch (AssertionFailedError t) {
411            threadRecordFailure(t);
412            throw t;
413        }
414    }
415
416    /**
417     * Just like assertEquals(x, y), but additionally recording (using
418     * threadRecordFailure) any AssertionFailedError thrown, so that
419     * the current testcase will fail.
420     */
421    public void threadAssertEquals(Object x, Object y) {
422        try {
423            assertEquals(x, y);
424        } catch (AssertionFailedError t) {
425            threadRecordFailure(t);
426            throw t;
427        } catch (Throwable t) {
428            threadUnexpectedException(t);
429        }
430    }
431
432    /**
433     * Just like assertSame(x, y), but additionally recording (using
434     * threadRecordFailure) any AssertionFailedError thrown, so that
435     * the current testcase will fail.
436     */
437    public void threadAssertSame(Object x, Object y) {
438        try {
439            assertSame(x, y);
440        } catch (AssertionFailedError t) {
441            threadRecordFailure(t);
442            throw t;
443        }
444    }
445
446    /**
447     * Calls threadFail with message "should throw exception".
448     */
449    public void threadShouldThrow() {
450        threadFail("should throw exception");
451    }
452
453    /**
454     * Calls threadFail with message "should throw" + exceptionName.
455     */
456    public void threadShouldThrow(String exceptionName) {
457        threadFail("should throw " + exceptionName);
458    }
459
460    /**
461     * Records the given exception using {@link #threadRecordFailure},
462     * then rethrows the exception, wrapping it in an
463     * AssertionFailedError if necessary.
464     */
465    public void threadUnexpectedException(Throwable t) {
466        threadRecordFailure(t);
467        t.printStackTrace();
468        if (t instanceof RuntimeException)
469            throw (RuntimeException) t;
470        else if (t instanceof Error)
471            throw (Error) t;
472        else {
473            AssertionFailedError afe =
474                new AssertionFailedError("unexpected exception: " + t);
475            afe.initCause(t);
476            throw afe;
477        }
478    }
479
480    /**
481     * Delays, via Thread.sleep, for the given millisecond delay, but
482     * if the sleep is shorter than specified, may re-sleep or yield
483     * until time elapses.
484     */
485    static void delay(long millis) throws InterruptedException {
486        long startTime = System.nanoTime();
487        long ns = millis * 1000 * 1000;
488        for (;;) {
489            if (millis > 0L)
490                Thread.sleep(millis);
491            else // too short to sleep
492                Thread.yield();
493            long d = ns - (System.nanoTime() - startTime);
494            if (d > 0L)
495                millis = d / (1000 * 1000);
496            else
497                break;
498        }
499    }
500
501    /**
502     * Waits out termination of a thread pool or fails doing so.
503     */
504    void joinPool(ExecutorService exec) {
505        try {
506            exec.shutdown();
507            assertTrue("ExecutorService did not terminate in a timely manner",
508                       exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS));
509        } catch (SecurityException ok) {
510            // Allowed in case test doesn't have privs
511        } catch (InterruptedException ie) {
512            fail("Unexpected InterruptedException");
513        }
514    }
515
516    /**
517     * Checks that thread does not terminate within the default
518     * millisecond delay of {@code timeoutMillis()}.
519     */
520    void assertThreadStaysAlive(Thread thread) {
521        assertThreadStaysAlive(thread, timeoutMillis());
522    }
523
524    /**
525     * Checks that thread does not terminate within the given millisecond delay.
526     */
527    void assertThreadStaysAlive(Thread thread, long millis) {
528        try {
529            // No need to optimize the failing case via Thread.join.
530            delay(millis);
531            assertTrue(thread.isAlive());
532        } catch (InterruptedException ie) {
533            fail("Unexpected InterruptedException");
534        }
535    }
536
537    /**
538     * Checks that the threads do not terminate within the default
539     * millisecond delay of {@code timeoutMillis()}.
540     */
541    void assertThreadsStayAlive(Thread... threads) {
542        assertThreadsStayAlive(timeoutMillis(), threads);
543    }
544
545    /**
546     * Checks that the threads do not terminate within the given millisecond delay.
547     */
548    void assertThreadsStayAlive(long millis, Thread... threads) {
549        try {
550            // No need to optimize the failing case via Thread.join.
551            delay(millis);
552            for (Thread thread : threads)
553                assertTrue(thread.isAlive());
554        } catch (InterruptedException ie) {
555            fail("Unexpected InterruptedException");
556        }
557    }
558
559    /**
560     * Checks that future.get times out, with the default timeout of
561     * {@code timeoutMillis()}.
562     */
563    void assertFutureTimesOut(Future future) {
564        assertFutureTimesOut(future, timeoutMillis());
565    }
566
567    /**
568     * Checks that future.get times out, with the given millisecond timeout.
569     */
570    void assertFutureTimesOut(Future future, long timeoutMillis) {
571        long startTime = System.nanoTime();
572        try {
573            future.get(timeoutMillis, MILLISECONDS);
574            shouldThrow();
575        } catch (TimeoutException success) {
576        } catch (Exception e) {
577            threadUnexpectedException(e);
578        } finally { future.cancel(true); }
579        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
580    }
581
582    /**
583     * Fails with message "should throw exception".
584     */
585    public void shouldThrow() {
586        fail("Should throw exception");
587    }
588
589    /**
590     * Fails with message "should throw " + exceptionName.
591     */
592    public void shouldThrow(String exceptionName) {
593        fail("Should throw " + exceptionName);
594    }
595
596    /**
597     * The number of elements to place in collections, arrays, etc.
598     */
599    public static final int SIZE = 20;
600
601    // Some convenient Integer constants
602
603    public static final Integer zero  = new Integer(0);
604    public static final Integer one   = new Integer(1);
605    public static final Integer two   = new Integer(2);
606    public static final Integer three = new Integer(3);
607    public static final Integer four  = new Integer(4);
608    public static final Integer five  = new Integer(5);
609    public static final Integer six   = new Integer(6);
610    public static final Integer seven = new Integer(7);
611    public static final Integer eight = new Integer(8);
612    public static final Integer nine  = new Integer(9);
613    public static final Integer m1  = new Integer(-1);
614    public static final Integer m2  = new Integer(-2);
615    public static final Integer m3  = new Integer(-3);
616    public static final Integer m4  = new Integer(-4);
617    public static final Integer m5  = new Integer(-5);
618    public static final Integer m6  = new Integer(-6);
619    public static final Integer m10 = new Integer(-10);
620
621    /**
622     * Runs Runnable r with a security policy that permits precisely
623     * the specified permissions.  If there is no current security
624     * manager, the runnable is run twice, both with and without a
625     * security manager.  We require that any security manager permit
626     * getPolicy/setPolicy.
627     */
628    public void runWithPermissions(Runnable r, Permission... permissions) {
629        SecurityManager sm = System.getSecurityManager();
630        if (sm == null) {
631            r.run();
632            Policy savedPolicy = Policy.getPolicy();
633            try {
634                Policy.setPolicy(permissivePolicy());
635                System.setSecurityManager(new SecurityManager());
636                runWithPermissions(r, permissions);
637            } finally {
638                System.setSecurityManager(null);
639                Policy.setPolicy(savedPolicy);
640            }
641        } else {
642            Policy savedPolicy = Policy.getPolicy();
643            AdjustablePolicy policy = new AdjustablePolicy(permissions);
644            Policy.setPolicy(policy);
645
646            try {
647                r.run();
648            } finally {
649                policy.addPermission(new SecurityPermission("setPolicy"));
650                Policy.setPolicy(savedPolicy);
651            }
652        }
653    }
654
655    /**
656     * Runs a runnable without any permissions.
657     */
658    public void runWithoutPermissions(Runnable r) {
659        runWithPermissions(r);
660    }
661
662    /**
663     * A security policy where new permissions can be dynamically added
664     * or all cleared.
665     */
666    public static class AdjustablePolicy extends java.security.Policy {
667        Permissions perms = new Permissions();
668        AdjustablePolicy(Permission... permissions) {
669            for (Permission permission : permissions)
670                perms.add(permission);
671        }
672        void addPermission(Permission perm) { perms.add(perm); }
673        void clearPermissions() { perms = new Permissions(); }
674        public PermissionCollection getPermissions(CodeSource cs) {
675            return perms;
676        }
677        public PermissionCollection getPermissions(ProtectionDomain pd) {
678            return perms;
679        }
680        public boolean implies(ProtectionDomain pd, Permission p) {
681            return perms.implies(p);
682        }
683        public void refresh() {}
684    }
685
686    /**
687     * Returns a policy containing all the permissions we ever need.
688     */
689    public static Policy permissivePolicy() {
690        return new AdjustablePolicy
691            // Permissions j.u.c. needs directly
692            (new RuntimePermission("modifyThread"),
693             new RuntimePermission("getClassLoader"),
694             new RuntimePermission("setContextClassLoader"),
695             // Permissions needed to change permissions!
696             new SecurityPermission("getPolicy"),
697             new SecurityPermission("setPolicy"),
698             new RuntimePermission("setSecurityManager"),
699             // Permissions needed by the junit test harness
700             new RuntimePermission("accessDeclaredMembers"),
701             new PropertyPermission("*", "read"),
702             new java.io.FilePermission("<<ALL FILES>>", "read"));
703    }
704
705    /**
706     * Sleeps until the given time has elapsed.
707     * Throws AssertionFailedError if interrupted.
708     */
709    void sleep(long millis) {
710        try {
711            delay(millis);
712        } catch (InterruptedException ie) {
713            AssertionFailedError afe =
714                new AssertionFailedError("Unexpected InterruptedException");
715            afe.initCause(ie);
716            throw afe;
717        }
718    }
719
720    /**
721     * Spin-waits up to the specified number of milliseconds for the given
722     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
723     */
724    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
725        long startTime = System.nanoTime();
726        for (;;) {
727            Thread.State s = thread.getState();
728            if (s == Thread.State.BLOCKED ||
729                s == Thread.State.WAITING ||
730                s == Thread.State.TIMED_WAITING)
731                return;
732            else if (s == Thread.State.TERMINATED)
733                fail("Unexpected thread termination");
734            else if (millisElapsedSince(startTime) > timeoutMillis) {
735                threadAssertTrue(thread.isAlive());
736                return;
737            }
738            Thread.yield();
739        }
740    }
741
742    /**
743     * Waits up to LONG_DELAY_MS for the given thread to enter a wait
744     * state: BLOCKED, WAITING, or TIMED_WAITING.
745     */
746    void waitForThreadToEnterWaitState(Thread thread) {
747        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
748    }
749
750    /**
751     * Returns the number of milliseconds since time given by
752     * startNanoTime, which must have been previously returned from a
753     * call to {@link System.nanoTime()}.
754     */
755    long millisElapsedSince(long startNanoTime) {
756        return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
757    }
758
759    /**
760     * Returns a new started daemon Thread running the given runnable.
761     */
762    Thread newStartedThread(Runnable runnable) {
763        Thread t = new Thread(runnable);
764        t.setDaemon(true);
765        t.start();
766        return t;
767    }
768
769    /**
770     * Waits for the specified time (in milliseconds) for the thread
771     * to terminate (using {@link Thread#join(long)}), else interrupts
772     * the thread (in the hope that it may terminate later) and fails.
773     */
774    void awaitTermination(Thread t, long timeoutMillis) {
775        try {
776            t.join(timeoutMillis);
777        } catch (InterruptedException ie) {
778            threadUnexpectedException(ie);
779        } finally {
780            if (t.getState() != Thread.State.TERMINATED) {
781                t.interrupt();
782                fail("Test timed out");
783            }
784        }
785    }
786
787    /**
788     * Waits for LONG_DELAY_MS milliseconds for the thread to
789     * terminate (using {@link Thread#join(long)}), else interrupts
790     * the thread (in the hope that it may terminate later) and fails.
791     */
792    void awaitTermination(Thread t) {
793        awaitTermination(t, LONG_DELAY_MS);
794    }
795
796    // Some convenient Runnable classes
797
798    public abstract class CheckedRunnable implements Runnable {
799        protected abstract void realRun() throws Throwable;
800
801        public final void run() {
802            try {
803                realRun();
804            } catch (Throwable t) {
805                threadUnexpectedException(t);
806            }
807        }
808    }
809
810    public abstract class RunnableShouldThrow implements Runnable {
811        protected abstract void realRun() throws Throwable;
812
813        final Class<?> exceptionClass;
814
815        <T extends Throwable> RunnableShouldThrow(Class<T> exceptionClass) {
816            this.exceptionClass = exceptionClass;
817        }
818
819        public final void run() {
820            try {
821                realRun();
822                threadShouldThrow(exceptionClass.getSimpleName());
823            } catch (Throwable t) {
824                if (! exceptionClass.isInstance(t))
825                    threadUnexpectedException(t);
826            }
827        }
828    }
829
830    public abstract class ThreadShouldThrow extends Thread {
831        protected abstract void realRun() throws Throwable;
832
833        final Class<?> exceptionClass;
834
835        <T extends Throwable> ThreadShouldThrow(Class<T> exceptionClass) {
836            this.exceptionClass = exceptionClass;
837        }
838
839        public final void run() {
840            try {
841                realRun();
842                threadShouldThrow(exceptionClass.getSimpleName());
843            } catch (Throwable t) {
844                if (! exceptionClass.isInstance(t))
845                    threadUnexpectedException(t);
846            }
847        }
848    }
849
850    public abstract class CheckedInterruptedRunnable implements Runnable {
851        protected abstract void realRun() throws Throwable;
852
853        public final void run() {
854            try {
855                realRun();
856                threadShouldThrow("InterruptedException");
857            } catch (InterruptedException success) {
858                threadAssertFalse(Thread.interrupted());
859            } catch (Throwable t) {
860                threadUnexpectedException(t);
861            }
862        }
863    }
864
865    public abstract class CheckedCallable<T> implements Callable<T> {
866        protected abstract T realCall() throws Throwable;
867
868        public final T call() {
869            try {
870                return realCall();
871            } catch (Throwable t) {
872                threadUnexpectedException(t);
873                return null;
874            }
875        }
876    }
877
878    public abstract class CheckedInterruptedCallable<T>
879        implements Callable<T> {
880        protected abstract T realCall() throws Throwable;
881
882        public final T call() {
883            try {
884                T result = realCall();
885                threadShouldThrow("InterruptedException");
886                return result;
887            } catch (InterruptedException success) {
888                threadAssertFalse(Thread.interrupted());
889            } catch (Throwable t) {
890                threadUnexpectedException(t);
891            }
892            return null;
893        }
894    }
895
896    public static class NoOpRunnable implements Runnable {
897        public void run() {}
898    }
899
900    public static class NoOpCallable implements Callable {
901        public Object call() { return Boolean.TRUE; }
902    }
903
904    public static final String TEST_STRING = "a test string";
905
906    public static class StringTask implements Callable<String> {
907        public String call() { return TEST_STRING; }
908    }
909
910    public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
911        return new CheckedCallable<String>() {
912            protected String realCall() {
913                try {
914                    latch.await();
915                } catch (InterruptedException quittingTime) {}
916                return TEST_STRING;
917            }};
918    }
919
920    public Runnable awaiter(final CountDownLatch latch) {
921        return new CheckedRunnable() {
922            public void realRun() throws InterruptedException {
923                await(latch);
924            }};
925    }
926
927    public void await(CountDownLatch latch) {
928        try {
929            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
930        } catch (Throwable t) {
931            threadUnexpectedException(t);
932        }
933    }
934
935    public void await(Semaphore semaphore) {
936        try {
937            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
938        } catch (Throwable t) {
939            threadUnexpectedException(t);
940        }
941    }
942
943//     /**
944//      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
945//      */
946//     public void await(AtomicBoolean flag) {
947//         await(flag, LONG_DELAY_MS);
948//     }
949
950//     /**
951//      * Spin-waits up to the specified timeout until flag becomes true.
952//      */
953//     public void await(AtomicBoolean flag, long timeoutMillis) {
954//         long startTime = System.nanoTime();
955//         while (!flag.get()) {
956//             if (millisElapsedSince(startTime) > timeoutMillis)
957//                 throw new AssertionFailedError("timed out");
958//             Thread.yield();
959//         }
960//     }
961
962    public static class NPETask implements Callable<String> {
963        public String call() { throw new NullPointerException(); }
964    }
965
966    public static class CallableOne implements Callable<Integer> {
967        public Integer call() { return one; }
968    }
969
970    public class ShortRunnable extends CheckedRunnable {
971        protected void realRun() throws Throwable {
972            delay(SHORT_DELAY_MS);
973        }
974    }
975
976    public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
977        protected void realRun() throws InterruptedException {
978            delay(SHORT_DELAY_MS);
979        }
980    }
981
982    public class SmallRunnable extends CheckedRunnable {
983        protected void realRun() throws Throwable {
984            delay(SMALL_DELAY_MS);
985        }
986    }
987
988    public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
989        protected void realRun() {
990            try {
991                delay(SMALL_DELAY_MS);
992            } catch (InterruptedException ok) {}
993        }
994    }
995
996    public class SmallCallable extends CheckedCallable {
997        protected Object realCall() throws InterruptedException {
998            delay(SMALL_DELAY_MS);
999            return Boolean.TRUE;
1000        }
1001    }
1002
1003    public class MediumRunnable extends CheckedRunnable {
1004        protected void realRun() throws Throwable {
1005            delay(MEDIUM_DELAY_MS);
1006        }
1007    }
1008
1009    public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1010        protected void realRun() throws InterruptedException {
1011            delay(MEDIUM_DELAY_MS);
1012        }
1013    }
1014
1015    public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1016        return new CheckedRunnable() {
1017            protected void realRun() {
1018                try {
1019                    delay(timeoutMillis);
1020                } catch (InterruptedException ok) {}
1021            }};
1022    }
1023
1024    public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1025        protected void realRun() {
1026            try {
1027                delay(MEDIUM_DELAY_MS);
1028            } catch (InterruptedException ok) {}
1029        }
1030    }
1031
1032    public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1033        protected void realRun() {
1034            try {
1035                delay(LONG_DELAY_MS);
1036            } catch (InterruptedException ok) {}
1037        }
1038    }
1039
1040    /**
1041     * For use as ThreadFactory in constructors
1042     */
1043    public static class SimpleThreadFactory implements ThreadFactory {
1044        public Thread newThread(Runnable r) {
1045            return new Thread(r);
1046        }
1047    }
1048
1049    public interface TrackedRunnable extends Runnable {
1050        boolean isDone();
1051    }
1052
1053    public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
1054        return new TrackedRunnable() {
1055                private volatile boolean done = false;
1056                public boolean isDone() { return done; }
1057                public void run() {
1058                    try {
1059                        delay(timeoutMillis);
1060                        done = true;
1061                    } catch (InterruptedException ok) {}
1062                }
1063            };
1064    }
1065
1066    public static class TrackedShortRunnable implements Runnable {
1067        public volatile boolean done = false;
1068        public void run() {
1069            try {
1070                delay(SHORT_DELAY_MS);
1071                done = true;
1072            } catch (InterruptedException ok) {}
1073        }
1074    }
1075
1076    public static class TrackedSmallRunnable implements Runnable {
1077        public volatile boolean done = false;
1078        public void run() {
1079            try {
1080                delay(SMALL_DELAY_MS);
1081                done = true;
1082            } catch (InterruptedException ok) {}
1083        }
1084    }
1085
1086    public static class TrackedMediumRunnable implements Runnable {
1087        public volatile boolean done = false;
1088        public void run() {
1089            try {
1090                delay(MEDIUM_DELAY_MS);
1091                done = true;
1092            } catch (InterruptedException ok) {}
1093        }
1094    }
1095
1096    public static class TrackedLongRunnable implements Runnable {
1097        public volatile boolean done = false;
1098        public void run() {
1099            try {
1100                delay(LONG_DELAY_MS);
1101                done = true;
1102            } catch (InterruptedException ok) {}
1103        }
1104    }
1105
1106    public static class TrackedNoOpRunnable implements Runnable {
1107        public volatile boolean done = false;
1108        public void run() {
1109            done = true;
1110        }
1111    }
1112
1113    public static class TrackedCallable implements Callable {
1114        public volatile boolean done = false;
1115        public Object call() {
1116            try {
1117                delay(SMALL_DELAY_MS);
1118                done = true;
1119            } catch (InterruptedException ok) {}
1120            return Boolean.TRUE;
1121        }
1122    }
1123
1124//     /**
1125//      * Analog of CheckedRunnable for RecursiveAction
1126//      */
1127//     public abstract class CheckedRecursiveAction extends RecursiveAction {
1128//         protected abstract void realCompute() throws Throwable;
1129
1130//         public final void compute() {
1131//             try {
1132//                 realCompute();
1133//             } catch (Throwable t) {
1134//                 threadUnexpectedException(t);
1135//             }
1136//         }
1137//     }
1138
1139//     /**
1140//      * Analog of CheckedCallable for RecursiveTask
1141//      */
1142//     public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1143//         protected abstract T realCompute() throws Throwable;
1144
1145//         public final T compute() {
1146//             try {
1147//                 return realCompute();
1148//             } catch (Throwable t) {
1149//                 threadUnexpectedException(t);
1150//                 return null;
1151//             }
1152//         }
1153//     }
1154
1155    /**
1156     * For use as RejectedExecutionHandler in constructors
1157     */
1158    public static class NoOpREHandler implements RejectedExecutionHandler {
1159        public void rejectedExecution(Runnable r,
1160                                      ThreadPoolExecutor executor) {}
1161    }
1162
1163    /**
1164     * A CyclicBarrier that uses timed await and fails with
1165     * AssertionFailedErrors instead of throwing checked exceptions.
1166     */
1167    public class CheckedBarrier extends CyclicBarrier {
1168        public CheckedBarrier(int parties) { super(parties); }
1169
1170        public int await() {
1171            try {
1172                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1173            } catch (TimeoutException e) {
1174                throw new AssertionFailedError("timed out");
1175            } catch (Exception e) {
1176                AssertionFailedError afe =
1177                    new AssertionFailedError("Unexpected exception: " + e);
1178                afe.initCause(e);
1179                throw afe;
1180            }
1181        }
1182    }
1183
1184    void checkEmpty(BlockingQueue q) {
1185        try {
1186            assertTrue(q.isEmpty());
1187            assertEquals(0, q.size());
1188            assertNull(q.peek());
1189            assertNull(q.poll());
1190            assertNull(q.poll(0, MILLISECONDS));
1191            assertEquals(q.toString(), "[]");
1192            assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1193            assertFalse(q.iterator().hasNext());
1194            try {
1195                q.element();
1196                shouldThrow();
1197            } catch (NoSuchElementException success) {}
1198            try {
1199                q.iterator().next();
1200                shouldThrow();
1201            } catch (NoSuchElementException success) {}
1202            try {
1203                q.remove();
1204                shouldThrow();
1205            } catch (NoSuchElementException success) {}
1206        } catch (InterruptedException ie) {
1207            threadUnexpectedException(ie);
1208        }
1209    }
1210
1211    @SuppressWarnings("unchecked")
1212    <T> T serialClone(T o) {
1213        try {
1214            ByteArrayOutputStream bos = new ByteArrayOutputStream();
1215            ObjectOutputStream oos = new ObjectOutputStream(bos);
1216            oos.writeObject(o);
1217            oos.flush();
1218            oos.close();
1219            ObjectInputStream ois = new ObjectInputStream
1220                (new ByteArrayInputStream(bos.toByteArray()));
1221            T clone = (T) ois.readObject();
1222            assertSame(o.getClass(), clone.getClass());
1223            return clone;
1224        } catch (Throwable t) {
1225            threadUnexpectedException(t);
1226            return null;
1227        }
1228    }
1229}
1230