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