• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 static java.util.concurrent.TimeUnit.MILLISECONDS;
12 import static java.util.concurrent.TimeUnit.NANOSECONDS;
13 
14 import java.io.ByteArrayInputStream;
15 import java.io.ByteArrayOutputStream;
16 import java.io.ObjectInputStream;
17 import java.io.ObjectOutputStream;
18 import java.lang.reflect.Method;
19 import java.security.CodeSource;
20 import java.security.Permission;
21 import java.security.PermissionCollection;
22 import java.security.Permissions;
23 import java.security.Policy;
24 import java.security.ProtectionDomain;
25 import java.security.SecurityPermission;
26 import java.util.ArrayList;
27 import java.util.Arrays;
28 import java.util.Date;
29 import java.util.Enumeration;
30 import java.util.Iterator;
31 import java.util.List;
32 import java.util.NoSuchElementException;
33 import java.util.PropertyPermission;
34 import java.util.concurrent.BlockingQueue;
35 import java.util.concurrent.Callable;
36 import java.util.concurrent.CountDownLatch;
37 import java.util.concurrent.CyclicBarrier;
38 import java.util.concurrent.ExecutorService;
39 import java.util.concurrent.Future;
40 import java.util.concurrent.RecursiveAction;
41 import java.util.concurrent.RecursiveTask;
42 import java.util.concurrent.RejectedExecutionHandler;
43 import java.util.concurrent.Semaphore;
44 import java.util.concurrent.ThreadFactory;
45 import java.util.concurrent.ThreadPoolExecutor;
46 import java.util.concurrent.TimeoutException;
47 import java.util.concurrent.atomic.AtomicReference;
48 import java.util.regex.Pattern;
49 
50 import junit.framework.AssertionFailedError;
51 import junit.framework.Test;
52 import junit.framework.TestCase;
53 import junit.framework.TestSuite;
54 
55 /**
56  * Base class for JSR166 Junit TCK tests.  Defines some constants,
57  * utility methods and classes, as well as a simple framework for
58  * helping to make sure that assertions failing in generated threads
59  * cause the associated test that generated them to itself fail (which
60  * JUnit does not otherwise arrange).  The rules for creating such
61  * tests are:
62  *
63  * <ol>
64  *
65  * <li> All assertions in code running in generated threads must use
66  * the forms {@link #threadFail}, {@link #threadAssertTrue}, {@link
67  * #threadAssertEquals}, or {@link #threadAssertNull}, (not
68  * {@code fail}, {@code assertTrue}, etc.) It is OK (but not
69  * particularly recommended) for other code to use these forms too.
70  * Only the most typically used JUnit assertion methods are defined
71  * this way, but enough to live with.</li>
72  *
73  * <li> If you override {@link #setUp} or {@link #tearDown}, make sure
74  * to invoke {@code super.setUp} and {@code super.tearDown} within
75  * them. These methods are used to clear and check for thread
76  * assertion failures.</li>
77  *
78  * <li>All delays and timeouts must use one of the constants {@code
79  * SHORT_DELAY_MS}, {@code SMALL_DELAY_MS}, {@code MEDIUM_DELAY_MS},
80  * {@code LONG_DELAY_MS}. The idea here is that a SHORT is always
81  * discriminable from zero time, and always allows enough time for the
82  * small amounts of computation (creating a thread, calling a few
83  * methods, etc) needed to reach a timeout point. Similarly, a SMALL
84  * is always discriminable as larger than SHORT and smaller than
85  * MEDIUM.  And so on. These constants are set to conservative values,
86  * but even so, if there is ever any doubt, they can all be increased
87  * in one spot to rerun tests on slower platforms.</li>
88  *
89  * <li> All threads generated must be joined inside each test case
90  * method (or {@code fail} to do so) before returning from the
91  * method. The {@code joinPool} method can be used to do this when
92  * using Executors.</li>
93  *
94  * </ol>
95  *
96  * <p><b>Other notes</b>
97  * <ul>
98  *
99  * <li> Usually, there is one testcase method per JSR166 method
100  * covering "normal" operation, and then as many exception-testing
101  * methods as there are exceptions the method can throw. Sometimes
102  * there are multiple tests per JSR166 method when the different
103  * "normal" behaviors differ significantly. And sometimes testcases
104  * cover multiple methods when they cannot be tested in
105  * isolation.</li>
106  *
107  * <li> The documentation style for testcases is to provide as javadoc
108  * a simple sentence or two describing the property that the testcase
109  * method purports to test. The javadocs do not say anything about how
110  * the property is tested. To find out, read the code.</li>
111  *
112  * <li> These tests are "conformance tests", and do not attempt to
113  * test throughput, latency, scalability or other performance factors
114  * (see the separate "jtreg" tests for a set intended to check these
115  * for the most central aspects of functionality.) So, most tests use
116  * the smallest sensible numbers of threads, collection sizes, etc
117  * needed to check basic conformance.</li>
118  *
119  * <li>The test classes currently do not declare inclusion in
120  * any particular package to simplify things for people integrating
121  * them in TCK test suites.</li>
122  *
123  * <li> As a convenience, the {@code main} of this class (JSR166TestCase)
124  * runs all JSR166 unit tests.</li>
125  *
126  * </ul>
127  */
128 public class JSR166TestCase extends TestCase {
129     // Delays for timing-dependent tests, in milliseconds.
130 
131     protected static final boolean expensiveTests = false;
132 
133     public static long SHORT_DELAY_MS;
134     public static long SMALL_DELAY_MS;
135     public static long MEDIUM_DELAY_MS;
136     public static long LONG_DELAY_MS;
137 
138     /**
139      * Returns the shortest timed delay. This could
140      * be reimplemented to use for example a Property.
141      */
getShortDelay()142     protected long getShortDelay() {
143         return 50;
144     }
145 
146     /**
147      * Sets delays as multiples of SHORT_DELAY.
148      */
setDelays()149     protected void setDelays() {
150         SHORT_DELAY_MS = getShortDelay();
151         SMALL_DELAY_MS  = SHORT_DELAY_MS * 5;
152         MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
153         LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
154     }
155 
156     /**
157      * Returns a timeout in milliseconds to be used in tests that
158      * verify that operations block or time out.
159      */
timeoutMillis()160     long timeoutMillis() {
161         return SHORT_DELAY_MS / 4;
162     }
163 
164     /**
165      * Returns a new Date instance representing a time delayMillis
166      * milliseconds in the future.
167      */
delayedDate(long delayMillis)168     Date delayedDate(long delayMillis) {
169         return new Date(System.currentTimeMillis() + delayMillis);
170     }
171 
172     /**
173      * The first exception encountered if any threadAssertXXX method fails.
174      */
175     private final AtomicReference<Throwable> threadFailure
176         = new AtomicReference<Throwable>(null);
177 
178     /**
179      * Records an exception so that it can be rethrown later in the test
180      * harness thread, triggering a test case failure.  Only the first
181      * failure is recorded; subsequent calls to this method from within
182      * the same test have no effect.
183      */
threadRecordFailure(Throwable t)184     public void threadRecordFailure(Throwable t) {
185         threadFailure.compareAndSet(null, t);
186     }
187 
setUp()188     public void setUp() {
189         setDelays();
190     }
191 
192     /**
193      * Extra checks that get done for all test cases.
194      *
195      * Triggers test case failure if any thread assertions have failed,
196      * by rethrowing, in the test harness thread, any exception recorded
197      * earlier by threadRecordFailure.
198      *
199      * Triggers test case failure if interrupt status is set in the main thread.
200      */
tearDown()201     public void tearDown() throws Exception {
202         Throwable t = threadFailure.getAndSet(null);
203         if (t != null) {
204             if (t instanceof Error)
205                 throw (Error) t;
206             else if (t instanceof RuntimeException)
207                 throw (RuntimeException) t;
208             else if (t instanceof Exception)
209                 throw (Exception) t;
210             else {
211                 AssertionFailedError afe =
212                     new AssertionFailedError(t.toString());
213                 afe.initCause(t);
214                 throw afe;
215             }
216         }
217 
218         if (Thread.interrupted())
219             throw new AssertionFailedError("interrupt status set in main thread");
220 
221         checkForkJoinPoolThreadLeaks();
222     }
223 
224     /**
225      * Finds missing try { ... } finally { joinPool(e); }
226      */
checkForkJoinPoolThreadLeaks()227     void checkForkJoinPoolThreadLeaks() throws InterruptedException {
228         Thread[] survivors = new Thread[5];
229         int count = Thread.enumerate(survivors);
230         for (int i = 0; i < count; i++) {
231             Thread thread = survivors[i];
232             String name = thread.getName();
233             if (name.startsWith("ForkJoinPool-")) {
234                 // give thread some time to terminate
235                 thread.join(LONG_DELAY_MS);
236                 if (!thread.isAlive()) continue;
237                 thread.stop();
238                 throw new AssertionFailedError
239                     (String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n",
240                                    toString(), name));
241             }
242         }
243     }
244 
245     /**
246      * Just like fail(reason), but additionally recording (using
247      * threadRecordFailure) any AssertionFailedError thrown, so that
248      * the current testcase will fail.
249      */
threadFail(String reason)250     public void threadFail(String reason) {
251         try {
252             fail(reason);
253         } catch (AssertionFailedError t) {
254             threadRecordFailure(t);
255             fail(reason);
256         }
257     }
258 
259     /**
260      * Just like assertTrue(b), but additionally recording (using
261      * threadRecordFailure) any AssertionFailedError thrown, so that
262      * the current testcase will fail.
263      */
threadAssertTrue(boolean b)264     public void threadAssertTrue(boolean b) {
265         try {
266             assertTrue(b);
267         } catch (AssertionFailedError t) {
268             threadRecordFailure(t);
269             throw t;
270         }
271     }
272 
273     /**
274      * Just like assertFalse(b), but additionally recording (using
275      * threadRecordFailure) any AssertionFailedError thrown, so that
276      * the current testcase will fail.
277      */
threadAssertFalse(boolean b)278     public void threadAssertFalse(boolean b) {
279         try {
280             assertFalse(b);
281         } catch (AssertionFailedError t) {
282             threadRecordFailure(t);
283             throw t;
284         }
285     }
286 
287     /**
288      * Just like assertNull(x), but additionally recording (using
289      * threadRecordFailure) any AssertionFailedError thrown, so that
290      * the current testcase will fail.
291      */
threadAssertNull(Object x)292     public void threadAssertNull(Object x) {
293         try {
294             assertNull(x);
295         } catch (AssertionFailedError t) {
296             threadRecordFailure(t);
297             throw t;
298         }
299     }
300 
301     /**
302      * Just like assertEquals(x, y), but additionally recording (using
303      * threadRecordFailure) any AssertionFailedError thrown, so that
304      * the current testcase will fail.
305      */
threadAssertEquals(long x, long y)306     public void threadAssertEquals(long x, long y) {
307         try {
308             assertEquals(x, y);
309         } catch (AssertionFailedError t) {
310             threadRecordFailure(t);
311             throw t;
312         }
313     }
314 
315     /**
316      * Just like assertEquals(x, y), but additionally recording (using
317      * threadRecordFailure) any AssertionFailedError thrown, so that
318      * the current testcase will fail.
319      */
threadAssertEquals(Object x, Object y)320     public void threadAssertEquals(Object x, Object y) {
321         try {
322             assertEquals(x, y);
323         } catch (AssertionFailedError fail) {
324             threadRecordFailure(fail);
325             throw fail;
326         } catch (Throwable fail) {
327             threadUnexpectedException(fail);
328         }
329     }
330 
331     /**
332      * Just like assertSame(x, y), but additionally recording (using
333      * threadRecordFailure) any AssertionFailedError thrown, so that
334      * the current testcase will fail.
335      */
threadAssertSame(Object x, Object y)336     public void threadAssertSame(Object x, Object y) {
337         try {
338             assertSame(x, y);
339         } catch (AssertionFailedError fail) {
340             threadRecordFailure(fail);
341             throw fail;
342         }
343     }
344 
345     /**
346      * Calls threadFail with message "should throw exception".
347      */
threadShouldThrow()348     public void threadShouldThrow() {
349         threadFail("should throw exception");
350     }
351 
352     /**
353      * Calls threadFail with message "should throw" + exceptionName.
354      */
threadShouldThrow(String exceptionName)355     public void threadShouldThrow(String exceptionName) {
356         threadFail("should throw " + exceptionName);
357     }
358 
359     /**
360      * Records the given exception using {@link #threadRecordFailure},
361      * then rethrows the exception, wrapping it in an
362      * AssertionFailedError if necessary.
363      */
threadUnexpectedException(Throwable t)364     public void threadUnexpectedException(Throwable t) {
365         threadRecordFailure(t);
366         t.printStackTrace();
367         if (t instanceof RuntimeException)
368             throw (RuntimeException) t;
369         else if (t instanceof Error)
370             throw (Error) t;
371         else {
372             AssertionFailedError afe =
373                 new AssertionFailedError("unexpected exception: " + t);
374             afe.initCause(t);
375             throw afe;
376         }
377     }
378 
379     /**
380      * Delays, via Thread.sleep, for the given millisecond delay, but
381      * if the sleep is shorter than specified, may re-sleep or yield
382      * until time elapses.
383      */
delay(long millis)384     static void delay(long millis) throws InterruptedException {
385         long startTime = System.nanoTime();
386         long ns = millis * 1000 * 1000;
387         for (;;) {
388             if (millis > 0L)
389                 Thread.sleep(millis);
390             else // too short to sleep
391                 Thread.yield();
392             long d = ns - (System.nanoTime() - startTime);
393             if (d > 0L)
394                 millis = d / (1000 * 1000);
395             else
396                 break;
397         }
398     }
399 
400     /**
401      * Waits out termination of a thread pool or fails doing so.
402      */
joinPool(ExecutorService exec)403     void joinPool(ExecutorService exec) {
404         try {
405             exec.shutdown();
406             if (!exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS))
407                 fail("ExecutorService " + exec +
408                      " did not terminate in a timely manner");
409         } catch (SecurityException ok) {
410             // Allowed in case test doesn't have privs
411         } catch (InterruptedException fail) {
412             fail("Unexpected InterruptedException");
413         }
414     }
415 
416     /**
417      * A debugging tool to print all stack traces, as jstack does.
418      */
printAllStackTraces()419     static void printAllStackTraces() {
420     }
421 
422     /**
423      * Checks that thread does not terminate within the default
424      * millisecond delay of {@code timeoutMillis()}.
425      */
assertThreadStaysAlive(Thread thread)426     void assertThreadStaysAlive(Thread thread) {
427         assertThreadStaysAlive(thread, timeoutMillis());
428     }
429 
430     /**
431      * Checks that thread does not terminate within the given millisecond delay.
432      */
assertThreadStaysAlive(Thread thread, long millis)433     void assertThreadStaysAlive(Thread thread, long millis) {
434         try {
435             // No need to optimize the failing case via Thread.join.
436             delay(millis);
437             assertTrue(thread.isAlive());
438         } catch (InterruptedException fail) {
439             fail("Unexpected InterruptedException");
440         }
441     }
442 
443     /**
444      * Checks that the threads do not terminate within the default
445      * millisecond delay of {@code timeoutMillis()}.
446      */
assertThreadsStayAlive(Thread... threads)447     void assertThreadsStayAlive(Thread... threads) {
448         assertThreadsStayAlive(timeoutMillis(), threads);
449     }
450 
451     /**
452      * Checks that the threads do not terminate within the given millisecond delay.
453      */
assertThreadsStayAlive(long millis, Thread... threads)454     void assertThreadsStayAlive(long millis, Thread... threads) {
455         try {
456             // No need to optimize the failing case via Thread.join.
457             delay(millis);
458             for (Thread thread : threads)
459                 assertTrue(thread.isAlive());
460         } catch (InterruptedException fail) {
461             fail("Unexpected InterruptedException");
462         }
463     }
464 
465     /**
466      * Checks that future.get times out, with the default timeout of
467      * {@code timeoutMillis()}.
468      */
assertFutureTimesOut(Future future)469     void assertFutureTimesOut(Future future) {
470         assertFutureTimesOut(future, timeoutMillis());
471     }
472 
473     /**
474      * Checks that future.get times out, with the given millisecond timeout.
475      */
assertFutureTimesOut(Future future, long timeoutMillis)476     void assertFutureTimesOut(Future future, long timeoutMillis) {
477         long startTime = System.nanoTime();
478         try {
479             future.get(timeoutMillis, MILLISECONDS);
480             shouldThrow();
481         } catch (TimeoutException success) {
482         } catch (Exception fail) {
483             threadUnexpectedException(fail);
484         } finally { future.cancel(true); }
485         assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
486     }
487 
488     /**
489      * Fails with message "should throw exception".
490      */
shouldThrow()491     public void shouldThrow() {
492         fail("Should throw exception");
493     }
494 
495     /**
496      * Fails with message "should throw " + exceptionName.
497      */
shouldThrow(String exceptionName)498     public void shouldThrow(String exceptionName) {
499         fail("Should throw " + exceptionName);
500     }
501 
502     /**
503      * The number of elements to place in collections, arrays, etc.
504      */
505     public static final int SIZE = 20;
506 
507     // Some convenient Integer constants
508 
509     public static final Integer zero  = new Integer(0);
510     public static final Integer one   = new Integer(1);
511     public static final Integer two   = new Integer(2);
512     public static final Integer three = new Integer(3);
513     public static final Integer four  = new Integer(4);
514     public static final Integer five  = new Integer(5);
515     public static final Integer six   = new Integer(6);
516     public static final Integer seven = new Integer(7);
517     public static final Integer eight = new Integer(8);
518     public static final Integer nine  = new Integer(9);
519     public static final Integer m1  = new Integer(-1);
520     public static final Integer m2  = new Integer(-2);
521     public static final Integer m3  = new Integer(-3);
522     public static final Integer m4  = new Integer(-4);
523     public static final Integer m5  = new Integer(-5);
524     public static final Integer m6  = new Integer(-6);
525     public static final Integer m10 = new Integer(-10);
526 
527     /**
528      * Runs Runnable r with a security policy that permits precisely
529      * the specified permissions.  If there is no current security
530      * manager, the runnable is run twice, both with and without a
531      * security manager.  We require that any security manager permit
532      * getPolicy/setPolicy.
533      */
runWithPermissions(Runnable r, Permission... permissions)534     public void runWithPermissions(Runnable r, Permission... permissions) {
535         r.run();
536     }
537 
538     /**
539      * Runs Runnable r with a security policy that permits precisely
540      * the specified permissions.  If there is no current security
541      * manager, a temporary one is set for the duration of the
542      * Runnable.  We require that any security manager permit
543      * getPolicy/setPolicy.
544      */
runWithSecurityManagerWithPermissions(Runnable r, Permission... permissions)545     public void runWithSecurityManagerWithPermissions(Runnable r,
546                                                       Permission... permissions) {
547         r.run();
548     }
549 
550     /**
551      * Runs a runnable without any permissions.
552      */
runWithoutPermissions(Runnable r)553     public void runWithoutPermissions(Runnable r) {
554         runWithPermissions(r);
555     }
556 
557     /**
558      * A security policy where new permissions can be dynamically added
559      * or all cleared.
560      */
561     public static class AdjustablePolicy extends java.security.Policy {
562         Permissions perms = new Permissions();
AdjustablePolicy(Permission... permissions)563         AdjustablePolicy(Permission... permissions) {
564             for (Permission permission : permissions)
565                 perms.add(permission);
566         }
addPermission(Permission perm)567         void addPermission(Permission perm) { perms.add(perm); }
clearPermissions()568         void clearPermissions() { perms = new Permissions(); }
getPermissions(CodeSource cs)569         public PermissionCollection getPermissions(CodeSource cs) {
570             return perms;
571         }
getPermissions(ProtectionDomain pd)572         public PermissionCollection getPermissions(ProtectionDomain pd) {
573             return perms;
574         }
implies(ProtectionDomain pd, Permission p)575         public boolean implies(ProtectionDomain pd, Permission p) {
576             return perms.implies(p);
577         }
refresh()578         public void refresh() {}
toString()579         public String toString() {
580             List<Permission> ps = new ArrayList<Permission>();
581             for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
582                 ps.add(e.nextElement());
583             return "AdjustablePolicy with permissions " + ps;
584         }
585     }
586 
587     /**
588      * Returns a policy containing all the permissions we ever need.
589      */
permissivePolicy()590     public static Policy permissivePolicy() {
591         return new AdjustablePolicy
592             // Permissions j.u.c. needs directly
593             (new RuntimePermission("modifyThread"),
594              new RuntimePermission("getClassLoader"),
595              new RuntimePermission("setContextClassLoader"),
596              // Permissions needed to change permissions!
597              new SecurityPermission("getPolicy"),
598              new SecurityPermission("setPolicy"),
599              new RuntimePermission("setSecurityManager"),
600              // Permissions needed by the junit test harness
601              new RuntimePermission("accessDeclaredMembers"),
602              new PropertyPermission("*", "read"),
603              new java.io.FilePermission("<<ALL FILES>>", "read"));
604     }
605 
606     /**
607      * Sleeps until the given time has elapsed.
608      * Throws AssertionFailedError if interrupted.
609      */
sleep(long millis)610     void sleep(long millis) {
611         try {
612             delay(millis);
613         } catch (InterruptedException fail) {
614             AssertionFailedError afe =
615                 new AssertionFailedError("Unexpected InterruptedException");
616             afe.initCause(fail);
617             throw afe;
618         }
619     }
620 
621     /**
622      * Spin-waits up to the specified number of milliseconds for the given
623      * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
624      */
waitForThreadToEnterWaitState(Thread thread, long timeoutMillis)625     void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
626         long startTime = System.nanoTime();
627         for (;;) {
628             Thread.State s = thread.getState();
629             if (s == Thread.State.BLOCKED ||
630                 s == Thread.State.WAITING ||
631                 s == Thread.State.TIMED_WAITING)
632                 return;
633             else if (s == Thread.State.TERMINATED)
634                 fail("Unexpected thread termination");
635             else if (millisElapsedSince(startTime) > timeoutMillis) {
636                 threadAssertTrue(thread.isAlive());
637                 return;
638             }
639             Thread.yield();
640         }
641     }
642 
643     /**
644      * Waits up to LONG_DELAY_MS for the given thread to enter a wait
645      * state: BLOCKED, WAITING, or TIMED_WAITING.
646      */
waitForThreadToEnterWaitState(Thread thread)647     void waitForThreadToEnterWaitState(Thread thread) {
648         waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
649     }
650 
651     /**
652      * Returns the number of milliseconds since time given by
653      * startNanoTime, which must have been previously returned from a
654      * call to {@link System#nanoTime()}.
655      */
millisElapsedSince(long startNanoTime)656     static long millisElapsedSince(long startNanoTime) {
657         return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
658     }
659 
660 //     void assertTerminatesPromptly(long timeoutMillis, Runnable r) {
661 //         long startTime = System.nanoTime();
662 //         try {
663 //             r.run();
664 //         } catch (Throwable fail) { threadUnexpectedException(fail); }
665 //         if (millisElapsedSince(startTime) > timeoutMillis/2)
666 //             throw new AssertionFailedError("did not return promptly");
667 //     }
668 
669 //     void assertTerminatesPromptly(Runnable r) {
670 //         assertTerminatesPromptly(LONG_DELAY_MS/2, r);
671 //     }
672 
673     /**
674      * Checks that timed f.get() returns the expected value, and does not
675      * wait for the timeout to elapse before returning.
676      */
checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis)677     <T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) {
678         long startTime = System.nanoTime();
679         try {
680             assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
681         } catch (Throwable fail) { threadUnexpectedException(fail); }
682         if (millisElapsedSince(startTime) > timeoutMillis/2)
683             throw new AssertionFailedError("timed get did not return promptly");
684     }
685 
checkTimedGet(Future<T> f, T expectedValue)686     <T> void checkTimedGet(Future<T> f, T expectedValue) {
687         checkTimedGet(f, expectedValue, LONG_DELAY_MS);
688     }
689 
690     /**
691      * Returns a new started daemon Thread running the given runnable.
692      */
newStartedThread(Runnable runnable)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      */
awaitTermination(Thread t, long timeoutMillis)705     void awaitTermination(Thread t, long timeoutMillis) {
706         try {
707             t.join(timeoutMillis);
708         } catch (InterruptedException fail) {
709             threadUnexpectedException(fail);
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      */
awaitTermination(Thread t)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 {
realRun()730         protected abstract void realRun() throws Throwable;
731 
run()732         public final void run() {
733             try {
734                 realRun();
735             } catch (Throwable fail) {
736                 threadUnexpectedException(fail);
737             }
738         }
739     }
740 
741     public abstract class RunnableShouldThrow implements Runnable {
realRun()742         protected abstract void realRun() throws Throwable;
743 
744         final Class<?> exceptionClass;
745 
RunnableShouldThrow(Class<T> exceptionClass)746         <T extends Throwable> RunnableShouldThrow(Class<T> exceptionClass) {
747             this.exceptionClass = exceptionClass;
748         }
749 
run()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 {
realRun()762         protected abstract void realRun() throws Throwable;
763 
764         final Class<?> exceptionClass;
765 
ThreadShouldThrow(Class<T> exceptionClass)766         <T extends Throwable> ThreadShouldThrow(Class<T> exceptionClass) {
767             this.exceptionClass = exceptionClass;
768         }
769 
run()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 {
realRun()782         protected abstract void realRun() throws Throwable;
783 
run()784         public final void run() {
785             try {
786                 realRun();
787                 threadShouldThrow("InterruptedException");
788             } catch (InterruptedException success) {
789                 threadAssertFalse(Thread.interrupted());
790             } catch (Throwable fail) {
791                 threadUnexpectedException(fail);
792             }
793         }
794     }
795 
796     public abstract class CheckedCallable<T> implements Callable<T> {
realCall()797         protected abstract T realCall() throws Throwable;
798 
call()799         public final T call() {
800             try {
801                 return realCall();
802             } catch (Throwable fail) {
803                 threadUnexpectedException(fail);
804                 return null;
805             }
806         }
807     }
808 
809     public abstract class CheckedInterruptedCallable<T>
810         implements Callable<T> {
realCall()811         protected abstract T realCall() throws Throwable;
812 
call()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 fail) {
821                 threadUnexpectedException(fail);
822             }
823             return null;
824         }
825     }
826 
827     public static class NoOpRunnable implements Runnable {
run()828         public void run() {}
829     }
830 
831     public static class NoOpCallable implements Callable {
call()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> {
call()838         public String call() { return TEST_STRING; }
839     }
840 
latchAwaitingStringTask(final CountDownLatch latch)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 fail) {
862             threadUnexpectedException(fail);
863         }
864     }
865 
866     public void await(Semaphore semaphore) {
867         try {
868             assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
869         } catch (Throwable fail) {
870             threadUnexpectedException(fail);
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         @Override protected final void compute() {
1062             try {
1063                 realCompute();
1064             } catch (Throwable fail) {
1065                 threadUnexpectedException(fail);
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         @Override protected final T compute() {
1077             try {
1078                 return realCompute();
1079             } catch (Throwable fail) {
1080                 threadUnexpectedException(fail);
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 timedOut) {
1105                 throw new AssertionFailedError("timed out");
1106             } catch (Exception fail) {
1107                 AssertionFailedError afe =
1108                     new AssertionFailedError("Unexpected exception: " + fail);
1109                 afe.initCause(fail);
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             assertEquals(q.toString(), "[]");
1123             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 fail) { threadUnexpectedException(fail); }
1138     }
1139 
1140     void assertSerialEquals(Object x, Object y) {
1141         assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1142     }
1143 
1144     void assertNotSerialEquals(Object x, Object y) {
1145         assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1146     }
1147 
1148     byte[] serialBytes(Object o) {
1149         try {
1150             ByteArrayOutputStream bos = new ByteArrayOutputStream();
1151             ObjectOutputStream oos = new ObjectOutputStream(bos);
1152             oos.writeObject(o);
1153             oos.flush();
1154             oos.close();
1155             return bos.toByteArray();
1156         } catch (Throwable fail) {
1157             threadUnexpectedException(fail);
1158             return new byte[0];
1159         }
1160     }
1161 
1162     @SuppressWarnings("unchecked")
1163     <T> T serialClone(T o) {
1164         try {
1165             ObjectInputStream ois = new ObjectInputStream
1166                 (new ByteArrayInputStream(serialBytes(o)));
1167             T clone = (T) ois.readObject();
1168             assertSame(o.getClass(), clone.getClass());
1169             return clone;
1170         } catch (Throwable fail) {
1171             threadUnexpectedException(fail);
1172             return null;
1173         }
1174     }
1175 
1176     public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1177                              Runnable... throwingActions) {
1178         for (Runnable throwingAction : throwingActions) {
1179             boolean threw = false;
1180             try { throwingAction.run(); }
1181             catch (Throwable t) {
1182                 threw = true;
1183                 if (!expectedExceptionClass.isInstance(t)) {
1184                     AssertionFailedError afe =
1185                         new AssertionFailedError
1186                         ("Expected " + expectedExceptionClass.getName() +
1187                          ", got " + t.getClass().getName());
1188                     afe.initCause(t);
1189                     threadUnexpectedException(afe);
1190                 }
1191             }
1192             if (!threw)
1193                 shouldThrow(expectedExceptionClass.getName());
1194         }
1195     }
1196 
1197     public void assertIteratorExhausted(Iterator<?> it) {
1198         try {
1199             it.next();
1200             shouldThrow();
1201         } catch (NoSuchElementException success) {}
1202         assertFalse(it.hasNext());
1203     }
1204 }
1205