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