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