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