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