ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck-jsr166e/JSR166TestCase.java
Revision: 1.8
Committed: Thu Feb 26 06:53:34 2015 UTC (9 years, 3 months ago) by jsr166
Branch: MAIN
Changes since 1.7: +0 -1 lines
Log Message:
delete unused imports

File Contents

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