ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck-jsr166e/JSR166TestCase.java
Revision: 1.4
Committed: Sun Nov 18 18:03:11 2012 UTC (11 years, 6 months ago) by jsr166
Branch: MAIN
Changes since 1.3: +1 -1 lines
Log Message:
normalize whitespace after <p>

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