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 package jsr166;
11 
12 import static java.util.concurrent.TimeUnit.MILLISECONDS;
13 import static java.util.concurrent.TimeUnit.MINUTES;
14 import static java.util.concurrent.TimeUnit.NANOSECONDS;
15 
16 import java.io.ByteArrayInputStream;
17 import java.io.ByteArrayOutputStream;
18 import java.io.ObjectInputStream;
19 import java.io.ObjectOutputStream;
20 import java.lang.reflect.Constructor;
21 import java.lang.reflect.Method;
22 import java.lang.reflect.Modifier;
23  import java.security.CodeSource;
24 import java.security.Permission;
25 import java.security.PermissionCollection;
26 import java.security.Permissions;
27 import java.security.Policy;
28 import java.security.ProtectionDomain;
29 import java.security.SecurityPermission;
30 import java.util.ArrayList;
31 import java.util.Arrays;
32 import java.util.Date;
33 import java.util.Enumeration;
34 import java.util.Iterator;
35 import java.util.List;
36 import java.util.NoSuchElementException;
37 import java.util.PropertyPermission;
38 import java.util.concurrent.BlockingQueue;
39 import java.util.concurrent.Callable;
40 import java.util.concurrent.CountDownLatch;
41 import java.util.concurrent.CyclicBarrier;
42 import java.util.concurrent.ExecutionException;
43 import java.util.concurrent.Executors;
44 import java.util.concurrent.ExecutorService;
45 import java.util.concurrent.ForkJoinPool;
46 import java.util.concurrent.Future;
47 import java.util.concurrent.RecursiveAction;
48 import java.util.concurrent.RecursiveTask;
49 import java.util.concurrent.RejectedExecutionHandler;
50 import java.util.concurrent.Semaphore;
51 import java.util.concurrent.ThreadFactory;
52 import java.util.concurrent.ThreadPoolExecutor;
53 import java.util.concurrent.TimeoutException;
54 import java.util.concurrent.atomic.AtomicBoolean;
55 import java.util.concurrent.atomic.AtomicReference;
56 import java.util.regex.Matcher;
57 import java.util.regex.Pattern;
58 
59 import junit.framework.AssertionFailedError;
60 import junit.framework.Test;
61 import junit.framework.TestCase;
62 import junit.framework.TestResult;
63 import junit.framework.TestSuite;
64 
65 /**
66  * Base class for JSR166 Junit TCK tests.  Defines some constants,
67  * utility methods and classes, as well as a simple framework for
68  * helping to make sure that assertions failing in generated threads
69  * cause the associated test that generated them to itself fail (which
70  * JUnit does not otherwise arrange).  The rules for creating such
71  * tests are:
72  *
73  * <ol>
74  *
75  * <li>All assertions in code running in generated threads must use
76  * the forms {@link #threadFail}, {@link #threadAssertTrue}, {@link
77  * #threadAssertEquals}, or {@link #threadAssertNull}, (not
78  * {@code fail}, {@code assertTrue}, etc.) It is OK (but not
79  * particularly recommended) for other code to use these forms too.
80  * Only the most typically used JUnit assertion methods are defined
81  * this way, but enough to live with.
82  *
83  * <li>If you override {@link #setUp} or {@link #tearDown}, make sure
84  * to invoke {@code super.setUp} and {@code super.tearDown} within
85  * them. These methods are used to clear and check for thread
86  * assertion failures.
87  *
88  * <li>All delays and timeouts must use one of the constants {@code
89  * SHORT_DELAY_MS}, {@code SMALL_DELAY_MS}, {@code MEDIUM_DELAY_MS},
90  * {@code LONG_DELAY_MS}. The idea here is that a SHORT is always
91  * discriminable from zero time, and always allows enough time for the
92  * small amounts of computation (creating a thread, calling a few
93  * methods, etc) needed to reach a timeout point. Similarly, a SMALL
94  * is always discriminable as larger than SHORT and smaller than
95  * MEDIUM.  And so on. These constants are set to conservative values,
96  * but even so, if there is ever any doubt, they can all be increased
97  * in one spot to rerun tests on slower platforms.
98  *
99  * <li>All threads generated must be joined inside each test case
100  * method (or {@code fail} to do so) before returning from the
101  * method. The {@code joinPool} method can be used to do this when
102  * using Executors.
103  *
104  * </ol>
105  *
106  * <p><b>Other notes</b>
107  * <ul>
108  *
109  * <li>Usually, there is one testcase method per JSR166 method
110  * covering "normal" operation, and then as many exception-testing
111  * methods as there are exceptions the method can throw. Sometimes
112  * there are multiple tests per JSR166 method when the different
113  * "normal" behaviors differ significantly. And sometimes testcases
114  * cover multiple methods when they cannot be tested in isolation.
115  *
116  * <li>The documentation style for testcases is to provide as javadoc
117  * a simple sentence or two describing the property that the testcase
118  * method purports to test. The javadocs do not say anything about how
119  * the property is tested. To find out, read the code.
120  *
121  * <li>These tests are "conformance tests", and do not attempt to
122  * test throughput, latency, scalability or other performance factors
123  * (see the separate "jtreg" tests for a set intended to check these
124  * for the most central aspects of functionality.) So, most tests use
125  * the smallest sensible numbers of threads, collection sizes, etc
126  * needed to check basic conformance.
127  *
128  * <li>The test classes currently do not declare inclusion in
129  * any particular package to simplify things for people integrating
130  * them in TCK test suites.
131  *
132  * <li>As a convenience, the {@code main} of this class (JSR166TestCase)
133  * runs all JSR166 unit tests.
134  *
135  * </ul>
136  */
137 public class JSR166TestCase extends TestCase {
138     private static final boolean useSecurityManager =
139         Boolean.getBoolean("jsr166.useSecurityManager");
140 
141     protected static final boolean expensiveTests =
142         Boolean.getBoolean("jsr166.expensiveTests");
143 
144     /**
145      * If true, also run tests that are not part of the official tck
146      * because they test unspecified implementation details.
147      */
148     protected static final boolean testImplementationDetails =
149         Boolean.getBoolean("jsr166.testImplementationDetails");
150 
151     /**
152      * If true, report on stdout all "slow" tests, that is, ones that
153      * take more than profileThreshold milliseconds to execute.
154      */
155     private static final boolean profileTests =
156         Boolean.getBoolean("jsr166.profileTests");
157 
158     /**
159      * The number of milliseconds that tests are permitted for
160      * execution without being reported, when profileTests is set.
161      */
162     private static final long profileThreshold =
163         Long.getLong("jsr166.profileThreshold", 100);
164 
165     /**
166      * The number of repetitions per test (for tickling rare bugs).
167      */
168     private static final int runsPerTest =
169         Integer.getInteger("jsr166.runsPerTest", 1);
170 
171     /**
172      * The number of repetitions of the test suite (for finding leaks?).
173      */
174     private static final int suiteRuns =
175         Integer.getInteger("jsr166.suiteRuns", 1);
176 
systemPropertyValue(String name, float defaultValue)177     private static float systemPropertyValue(String name, float defaultValue) {
178         String floatString = System.getProperty(name);
179         if (floatString == null)
180             return defaultValue;
181         try {
182             return Float.parseFloat(floatString);
183         } catch (NumberFormatException ex) {
184             throw new IllegalArgumentException(
185                 String.format("Bad float value in system property %s=%s",
186                               name, floatString));
187         }
188     }
189 
190     /**
191      * The scaling factor to apply to standard delays used in tests.
192      */
193     private static final float delayFactor =
194         systemPropertyValue("jsr166.delay.factor", 1.0f);
195 
196     /**
197      * The timeout factor as used in the jtreg test harness.
198      * See: http://openjdk.java.net/jtreg/tag-spec.html
199      */
200     private static final float jtregTestTimeoutFactor
201         = systemPropertyValue("test.timeout.factor", 1.0f);
202 
JSR166TestCase()203     public JSR166TestCase() { super(); }
JSR166TestCase(String name)204     public JSR166TestCase(String name) { super(name); }
205 
206     /**
207      * A filter for tests to run, matching strings of the form
208      * methodName(className), e.g. "testInvokeAll5(ForkJoinPoolTest)"
209      * Usefully combined with jsr166.runsPerTest.
210      */
211     private static final Pattern methodFilter = methodFilter();
212 
methodFilter()213     private static Pattern methodFilter() {
214         String regex = System.getProperty("jsr166.methodFilter");
215         return (regex == null) ? null : Pattern.compile(regex);
216     }
217 
218     // Instrumentation to debug very rare, but very annoying hung test runs.
219     static volatile TestCase currentTestCase;
220     // static volatile int currentRun = 0;
221     static {
222         Runnable checkForWedgedTest = new Runnable() { public void run() {
223             // Avoid spurious reports with enormous runsPerTest.
224             // A single test case run should never take more than 1 second.
225             // But let's cap it at the high end too ...
226             final int timeoutMinutes =
227                 Math.min(15, Math.max(runsPerTest / 60, 1));
228             for (TestCase lastTestCase = currentTestCase;;) {
229                 try { MINUTES.sleep(timeoutMinutes); }
230                 catch (InterruptedException unexpected) { break; }
231                 if (lastTestCase == currentTestCase) {
232                     System.err.printf(
233                         "Looks like we're stuck running test: %s%n",
234                         lastTestCase);
235 //                     System.err.printf(
236 //                         "Looks like we're stuck running test: %s (%d/%d)%n",
237 //                         lastTestCase, currentRun, runsPerTest);
238 //                     System.err.println("availableProcessors=" +
239 //                         Runtime.getRuntime().availableProcessors());
240 //                     System.err.printf("cpu model = %s%n", cpuModel());
241                     dumpTestThreads();
242                     // one stack dump is probably enough; more would be spam
243                     break;
244                 }
245                 lastTestCase = currentTestCase;
246             }}};
247         Thread thread = new Thread(checkForWedgedTest, "checkForWedgedTest");
248         thread.setDaemon(true);
thread.start()249         thread.start();
250     }
251 
252 //     public static String cpuModel() {
253 //         try {
254 //             Matcher matcher = Pattern.compile("model name\\s*: (.*)")
255 //                 .matcher(new String(
256 //                      Files.readAllBytes(Paths.get("/proc/cpuinfo")), "UTF-8"));
257 //             matcher.find();
258 //             return matcher.group(1);
259 //         } catch (Exception ex) { return null; }
260 //     }
261 
runBare()262     public void runBare() throws Throwable {
263         currentTestCase = this;
264         if (methodFilter == null
265             || methodFilter.matcher(toString()).find())
266             super.runBare();
267     }
268 
runTest()269     protected void runTest() throws Throwable {
270         for (int i = 0; i < runsPerTest; i++) {
271             // currentRun = i;
272             if (profileTests)
273                 runTestProfiled();
274             else
275                 super.runTest();
276         }
277     }
278 
runTestProfiled()279     protected void runTestProfiled() throws Throwable {
280         for (int i = 0; i < 2; i++) {
281             long startTime = System.nanoTime();
282             super.runTest();
283             long elapsedMillis = millisElapsedSince(startTime);
284             if (elapsedMillis < profileThreshold)
285                 break;
286             // Never report first run of any test; treat it as a
287             // warmup run, notably to trigger all needed classloading,
288             if (i > 0)
289                 System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
290         }
291     }
292 
293     /**
294      * Runs all JSR166 unit tests using junit.textui.TestRunner.
295      */
296     // android-note: Removed because no junit.textui
297     // public static void main(String[] args) {
298     //     main(suite(), args);
299     // }
300 
301     // static class PithyResultPrinter extends junit.textui.ResultPrinter {
302     //     PithyResultPrinter(java.io.PrintStream writer) { super(writer); }
303     //     long runTime;
304     //     public void startTest(Test test) {}
305     //     protected void printHeader(long runTime) {
306     //         this.runTime = runTime; // defer printing for later
307     //     }
308     //     protected void printFooter(TestResult result) {
309     //         if (result.wasSuccessful()) {
310     //             getWriter().println("OK (" + result.runCount() + " tests)"
311     //                 + "  Time: " + elapsedTimeAsString(runTime));
312     //         } else {
313     //             getWriter().println("Time: " + elapsedTimeAsString(runTime));
314     //             super.printFooter(result);
315     //         }
316     //     }
317     // }
318 
319     /**
320      * Returns a TestRunner that doesn't bother with unnecessary
321      * fluff, like printing a "." for each test case.
322      */
323     // static junit.textui.TestRunner newPithyTestRunner() {
324     //     junit.textui.TestRunner runner = new junit.textui.TestRunner();
325     //     runner.setPrinter(new PithyResultPrinter(System.out));
326     //     return runner;
327     // }
328 
329     /**
330      * Runs all unit tests in the given test suite.
331      * Actual behavior influenced by jsr166.* system properties.
332      */
333     // static void main(Test suite, String[] args) {
334     //     if (useSecurityManager) {
335     //         System.err.println("Setting a permissive security manager");
336     //         Policy.setPolicy(permissivePolicy());
337     //         System.setSecurityManager(new SecurityManager());
338     //     }
339     //     for (int i = 0; i < suiteRuns; i++) {
340     //         TestResult result = newPithyTestRunner().doRun(suite);
341     //         if (!result.wasSuccessful())
342     //             System.exit(1);
343     //         System.gc();
344     //         System.runFinalization();
345     //     }
346     // }
347 
newTestSuite(Object... suiteOrClasses)348     public static TestSuite newTestSuite(Object... suiteOrClasses) {
349         TestSuite suite = new TestSuite();
350         for (Object suiteOrClass : suiteOrClasses) {
351             if (suiteOrClass instanceof TestSuite)
352                 suite.addTest((TestSuite) suiteOrClass);
353             else if (suiteOrClass instanceof Class)
354                 suite.addTest(new TestSuite((Class<?>) suiteOrClass));
355             else
356                 throw new ClassCastException("not a test suite or class");
357         }
358         return suite;
359     }
360 
addNamedTestClasses(TestSuite suite, String... testClassNames)361     public static void addNamedTestClasses(TestSuite suite,
362                                            String... testClassNames) {
363         for (String testClassName : testClassNames) {
364             try {
365                 Class<?> testClass = Class.forName(testClassName);
366                 Method m = testClass.getDeclaredMethod("suite",
367                                                        new Class<?>[0]);
368                 suite.addTest(newTestSuite((Test)m.invoke(null)));
369             } catch (Exception e) {
370                 throw new Error("Missing test class", e);
371             }
372         }
373     }
374 
375     public static final double JAVA_CLASS_VERSION;
376     public static final String JAVA_SPECIFICATION_VERSION;
377     static {
378         try {
379             JAVA_CLASS_VERSION = java.security.AccessController.doPrivileged(
380                 new java.security.PrivilegedAction<Double>() {
381                 public Double run() {
382                     return Double.valueOf(System.getProperty("java.class.version"));}});
383             JAVA_SPECIFICATION_VERSION = java.security.AccessController.doPrivileged(
384                 new java.security.PrivilegedAction<String>() {
385                 public String run() {
386                     return System.getProperty("java.specification.version");}});
387         } catch (Throwable t) {
388             throw new Error(t);
389         }
390     }
391 
atLeastJava6()392     public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
atLeastJava7()393     public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
atLeastJava8()394     public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
atLeastJava9()395     public static boolean atLeastJava9() {
396         return JAVA_CLASS_VERSION >= 53.0
397             // As of 2015-09, java9 still uses 52.0 class file version
398             || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?(9|[0-9][0-9])$");
399     }
atLeastJava10()400     public static boolean atLeastJava10() {
401         return JAVA_CLASS_VERSION >= 54.0
402             || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?[0-9][0-9]$");
403     }
404 
405     /**
406      * Collects all JSR166 unit tests as one suite.
407      */
408     // android-note: Removed because the CTS runner does a bad job of
409     // public static Test suite() {
410     //     // Java7+ test classes
411     //     TestSuite suite = newTestSuite(
412     //         ForkJoinPoolTest.suite(),
413     //         ForkJoinTaskTest.suite(),
414     //         RecursiveActionTest.suite(),
415     //         RecursiveTaskTest.suite(),
416     //         LinkedTransferQueueTest.suite(),
417     //         PhaserTest.suite(),
418     //         ThreadLocalRandomTest.suite(),
419     //         AbstractExecutorServiceTest.suite(),
420     //         AbstractQueueTest.suite(),
421     //         AbstractQueuedSynchronizerTest.suite(),
422     //         AbstractQueuedLongSynchronizerTest.suite(),
423     //         ArrayBlockingQueueTest.suite(),
424     //         ArrayDequeTest.suite(),
425     //         AtomicBooleanTest.suite(),
426     //         AtomicIntegerArrayTest.suite(),
427     //         AtomicIntegerFieldUpdaterTest.suite(),
428     //         AtomicIntegerTest.suite(),
429     //         AtomicLongArrayTest.suite(),
430     //         AtomicLongFieldUpdaterTest.suite(),
431     //         AtomicLongTest.suite(),
432     //         AtomicMarkableReferenceTest.suite(),
433     //         AtomicReferenceArrayTest.suite(),
434     //         AtomicReferenceFieldUpdaterTest.suite(),
435     //         AtomicReferenceTest.suite(),
436     //         AtomicStampedReferenceTest.suite(),
437     //         ConcurrentHashMapTest.suite(),
438     //         ConcurrentLinkedDequeTest.suite(),
439     //         ConcurrentLinkedQueueTest.suite(),
440     //         ConcurrentSkipListMapTest.suite(),
441     //         ConcurrentSkipListSubMapTest.suite(),
442     //         ConcurrentSkipListSetTest.suite(),
443     //         ConcurrentSkipListSubSetTest.suite(),
444     //         CopyOnWriteArrayListTest.suite(),
445     //         CopyOnWriteArraySetTest.suite(),
446     //         CountDownLatchTest.suite(),
447     //         CyclicBarrierTest.suite(),
448     //         DelayQueueTest.suite(),
449     //         EntryTest.suite(),
450     //         ExchangerTest.suite(),
451     //         ExecutorsTest.suite(),
452     //         ExecutorCompletionServiceTest.suite(),
453     //         FutureTaskTest.suite(),
454     //         LinkedBlockingDequeTest.suite(),
455     //         LinkedBlockingQueueTest.suite(),
456     //         LinkedListTest.suite(),
457     //         LockSupportTest.suite(),
458     //         PriorityBlockingQueueTest.suite(),
459     //         PriorityQueueTest.suite(),
460     //         ReentrantLockTest.suite(),
461     //         ReentrantReadWriteLockTest.suite(),
462     //         ScheduledExecutorTest.suite(),
463     //         ScheduledExecutorSubclassTest.suite(),
464     //         SemaphoreTest.suite(),
465     //         SynchronousQueueTest.suite(),
466     //         SystemTest.suite(),
467     //         ThreadLocalTest.suite(),
468     //         ThreadPoolExecutorTest.suite(),
469     //         ThreadPoolExecutorSubclassTest.suite(),
470     //         ThreadTest.suite(),
471     //         TimeUnitTest.suite(),
472     //         TreeMapTest.suite(),
473     //         TreeSetTest.suite(),
474     //         TreeSubMapTest.suite(),
475     //         TreeSubSetTest.suite());
476 
477     //     // Java8+ test classes
478     //     if (atLeastJava8()) {
479     //         String[] java8TestClassNames = {
480     //             "Atomic8Test",
481     //             "CompletableFutureTest",
482     //             "ConcurrentHashMap8Test",
483     //             "CountedCompleterTest",
484     //             "DoubleAccumulatorTest",
485     //             "DoubleAdderTest",
486     //             "ForkJoinPool8Test",
487     //             "ForkJoinTask8Test",
488     //             "LongAccumulatorTest",
489     //             "LongAdderTest",
490     //             "SplittableRandomTest",
491     //             "StampedLockTest",
492     //             "SubmissionPublisherTest",
493     //             "ThreadLocalRandom8Test",
494     //         };
495     //         addNamedTestClasses(suite, java8TestClassNames);
496     //     }
497 
498     //     // Java9+ test classes
499     //     if (atLeastJava9()) {
500     //         String[] java9TestClassNames = {
501     //             // Currently empty, but expecting varhandle tests
502     //         };
503     //         addNamedTestClasses(suite, java9TestClassNames);
504     //     }
505 
506     //     return suite;
507     // }
508 
509     /** Returns list of junit-style test method names in given class. */
testMethodNames(Class<?> testClass)510     public static ArrayList<String> testMethodNames(Class<?> testClass) {
511         Method[] methods = testClass.getDeclaredMethods();
512         ArrayList<String> names = new ArrayList<String>(methods.length);
513         for (Method method : methods) {
514             if (method.getName().startsWith("test")
515                 && Modifier.isPublic(method.getModifiers())
516                 // method.getParameterCount() requires jdk8+
517                 && method.getParameterTypes().length == 0) {
518                 names.add(method.getName());
519             }
520         }
521         return names;
522     }
523 
524     /**
525      * Returns junit-style testSuite for the given test class, but
526      * parameterized by passing extra data to each test.
527      */
parameterizedTestSuite(Class<? extends JSR166TestCase> testClass, Class<ExtraData> dataClass, ExtraData data)528     public static <ExtraData> Test parameterizedTestSuite
529         (Class<? extends JSR166TestCase> testClass,
530          Class<ExtraData> dataClass,
531          ExtraData data) {
532         try {
533             TestSuite suite = new TestSuite();
534             Constructor c =
535                 testClass.getDeclaredConstructor(dataClass, String.class);
536             for (String methodName : testMethodNames(testClass))
537                 suite.addTest((Test) c.newInstance(data, methodName));
538             return suite;
539         } catch (Exception e) {
540             throw new Error(e);
541         }
542     }
543 
544     /**
545      * Returns junit-style testSuite for the jdk8 extension of the
546      * given test class, but parameterized by passing extra data to
547      * each test.  Uses reflection to allow compilation in jdk7.
548      */
jdk8ParameterizedTestSuite(Class<? extends JSR166TestCase> testClass, Class<ExtraData> dataClass, ExtraData data)549     public static <ExtraData> Test jdk8ParameterizedTestSuite
550         (Class<? extends JSR166TestCase> testClass,
551          Class<ExtraData> dataClass,
552          ExtraData data) {
553         if (atLeastJava8()) {
554             String name = testClass.getName();
555             String name8 = name.replaceAll("Test$", "8Test");
556             if (name.equals(name8)) throw new Error(name);
557             try {
558                 return (Test)
559                     Class.forName(name8)
560                     .getMethod("testSuite", new Class[] { dataClass })
561                     .invoke(null, data);
562             } catch (Exception e) {
563                 throw new Error(e);
564             }
565         } else {
566             return new TestSuite();
567         }
568     }
569 
570     // Delays for timing-dependent tests, in milliseconds.
571 
572     public static long SHORT_DELAY_MS;
573     public static long SMALL_DELAY_MS;
574     public static long MEDIUM_DELAY_MS;
575     public static long LONG_DELAY_MS;
576 
577     /**
578      * Returns the shortest timed delay. This can be scaled up for
579      * slow machines using the jsr166.delay.factor system property,
580      * or via jtreg's -timeoutFactor: flag.
581      * http://openjdk.java.net/jtreg/command-help.html
582      */
getShortDelay()583     protected long getShortDelay() {
584         return (long) (50 * delayFactor * jtregTestTimeoutFactor);
585     }
586 
587     /**
588      * Sets delays as multiples of SHORT_DELAY.
589      */
setDelays()590     protected void setDelays() {
591         SHORT_DELAY_MS = getShortDelay();
592         SMALL_DELAY_MS  = SHORT_DELAY_MS * 5;
593         MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
594         LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
595     }
596 
597     /**
598      * Returns a timeout in milliseconds to be used in tests that
599      * verify that operations block or time out.
600      */
timeoutMillis()601     long timeoutMillis() {
602         return SHORT_DELAY_MS / 4;
603     }
604 
605     /**
606      * Returns a new Date instance representing a time at least
607      * delayMillis milliseconds in the future.
608      */
delayedDate(long delayMillis)609     Date delayedDate(long delayMillis) {
610         // Add 1 because currentTimeMillis is known to round into the past.
611         return new Date(System.currentTimeMillis() + delayMillis + 1);
612     }
613 
614     /**
615      * The first exception encountered if any threadAssertXXX method fails.
616      */
617     private final AtomicReference<Throwable> threadFailure
618         = new AtomicReference<Throwable>(null);
619 
620     /**
621      * Records an exception so that it can be rethrown later in the test
622      * harness thread, triggering a test case failure.  Only the first
623      * failure is recorded; subsequent calls to this method from within
624      * the same test have no effect.
625      */
threadRecordFailure(Throwable t)626     public void threadRecordFailure(Throwable t) {
627         System.err.println(t);
628         dumpTestThreads();
629         threadFailure.compareAndSet(null, t);
630     }
631 
setUp()632     public void setUp() {
633         setDelays();
634     }
635 
tearDownFail(String format, Object... args)636     void tearDownFail(String format, Object... args) {
637         String msg = toString() + ": " + String.format(format, args);
638         System.err.println(msg);
639         dumpTestThreads();
640         throw new AssertionFailedError(msg);
641     }
642 
643     /**
644      * Extra checks that get done for all test cases.
645      *
646      * Triggers test case failure if any thread assertions have failed,
647      * by rethrowing, in the test harness thread, any exception recorded
648      * earlier by threadRecordFailure.
649      *
650      * Triggers test case failure if interrupt status is set in the main thread.
651      */
tearDown()652     public void tearDown() throws Exception {
653         Throwable t = threadFailure.getAndSet(null);
654         if (t != null) {
655             if (t instanceof Error)
656                 throw (Error) t;
657             else if (t instanceof RuntimeException)
658                 throw (RuntimeException) t;
659             else if (t instanceof Exception)
660                 throw (Exception) t;
661             else {
662                 AssertionFailedError afe =
663                     new AssertionFailedError(t.toString());
664                 afe.initCause(t);
665                 throw afe;
666             }
667         }
668 
669         if (Thread.interrupted())
670             tearDownFail("interrupt status set in main thread");
671 
672         checkForkJoinPoolThreadLeaks();
673     }
674 
675     /**
676      * Finds missing PoolCleaners
677      */
checkForkJoinPoolThreadLeaks()678     void checkForkJoinPoolThreadLeaks() throws InterruptedException {
679         Thread[] survivors = new Thread[7];
680         int count = Thread.enumerate(survivors);
681         for (int i = 0; i < count; i++) {
682             Thread thread = survivors[i];
683             String name = thread.getName();
684             if (name.startsWith("ForkJoinPool-")) {
685                 // give thread some time to terminate
686                 thread.join(LONG_DELAY_MS);
687                 if (thread.isAlive())
688                     tearDownFail("Found leaked ForkJoinPool thread thread=%s",
689                                  thread);
690             }
691         }
692 
693         if (!ForkJoinPool.commonPool()
694             .awaitQuiescence(LONG_DELAY_MS, MILLISECONDS))
695             tearDownFail("ForkJoin common pool thread stuck");
696     }
697 
698     /**
699      * Just like fail(reason), but additionally recording (using
700      * threadRecordFailure) any AssertionFailedError thrown, so that
701      * the current testcase will fail.
702      */
threadFail(String reason)703     public void threadFail(String reason) {
704         try {
705             fail(reason);
706         } catch (AssertionFailedError t) {
707             threadRecordFailure(t);
708             throw t;
709         }
710     }
711 
712     /**
713      * Just like assertTrue(b), but additionally recording (using
714      * threadRecordFailure) any AssertionFailedError thrown, so that
715      * the current testcase will fail.
716      */
threadAssertTrue(boolean b)717     public void threadAssertTrue(boolean b) {
718         try {
719             assertTrue(b);
720         } catch (AssertionFailedError t) {
721             threadRecordFailure(t);
722             throw t;
723         }
724     }
725 
726     /**
727      * Just like assertFalse(b), but additionally recording (using
728      * threadRecordFailure) any AssertionFailedError thrown, so that
729      * the current testcase will fail.
730      */
threadAssertFalse(boolean b)731     public void threadAssertFalse(boolean b) {
732         try {
733             assertFalse(b);
734         } catch (AssertionFailedError t) {
735             threadRecordFailure(t);
736             throw t;
737         }
738     }
739 
740     /**
741      * Just like assertNull(x), but additionally recording (using
742      * threadRecordFailure) any AssertionFailedError thrown, so that
743      * the current testcase will fail.
744      */
threadAssertNull(Object x)745     public void threadAssertNull(Object x) {
746         try {
747             assertNull(x);
748         } catch (AssertionFailedError t) {
749             threadRecordFailure(t);
750             throw t;
751         }
752     }
753 
754     /**
755      * Just like assertEquals(x, y), but additionally recording (using
756      * threadRecordFailure) any AssertionFailedError thrown, so that
757      * the current testcase will fail.
758      */
threadAssertEquals(long x, long y)759     public void threadAssertEquals(long x, long y) {
760         try {
761             assertEquals(x, y);
762         } catch (AssertionFailedError t) {
763             threadRecordFailure(t);
764             throw t;
765         }
766     }
767 
768     /**
769      * Just like assertEquals(x, y), but additionally recording (using
770      * threadRecordFailure) any AssertionFailedError thrown, so that
771      * the current testcase will fail.
772      */
threadAssertEquals(Object x, Object y)773     public void threadAssertEquals(Object x, Object y) {
774         try {
775             assertEquals(x, y);
776         } catch (AssertionFailedError fail) {
777             threadRecordFailure(fail);
778             throw fail;
779         } catch (Throwable fail) {
780             threadUnexpectedException(fail);
781         }
782     }
783 
784     /**
785      * Just like assertSame(x, y), but additionally recording (using
786      * threadRecordFailure) any AssertionFailedError thrown, so that
787      * the current testcase will fail.
788      */
threadAssertSame(Object x, Object y)789     public void threadAssertSame(Object x, Object y) {
790         try {
791             assertSame(x, y);
792         } catch (AssertionFailedError fail) {
793             threadRecordFailure(fail);
794             throw fail;
795         }
796     }
797 
798     /**
799      * Calls threadFail with message "should throw exception".
800      */
threadShouldThrow()801     public void threadShouldThrow() {
802         threadFail("should throw exception");
803     }
804 
805     /**
806      * Calls threadFail with message "should throw" + exceptionName.
807      */
threadShouldThrow(String exceptionName)808     public void threadShouldThrow(String exceptionName) {
809         threadFail("should throw " + exceptionName);
810     }
811 
812     /**
813      * Records the given exception using {@link #threadRecordFailure},
814      * then rethrows the exception, wrapping it in an
815      * AssertionFailedError if necessary.
816      */
threadUnexpectedException(Throwable t)817     public void threadUnexpectedException(Throwable t) {
818         threadRecordFailure(t);
819         t.printStackTrace();
820         if (t instanceof RuntimeException)
821             throw (RuntimeException) t;
822         else if (t instanceof Error)
823             throw (Error) t;
824         else {
825             AssertionFailedError afe =
826                 new AssertionFailedError("unexpected exception: " + t);
827             afe.initCause(t);
828             throw afe;
829         }
830     }
831 
832     /**
833      * Delays, via Thread.sleep, for the given millisecond delay, but
834      * if the sleep is shorter than specified, may re-sleep or yield
835      * until time elapses.  Ensures that the given time, as measured
836      * by System.nanoTime(), has elapsed.
837      */
delay(long millis)838     static void delay(long millis) throws InterruptedException {
839         long nanos = millis * (1000 * 1000);
840         final long wakeupTime = System.nanoTime() + nanos;
841         do {
842             if (millis > 0L)
843                 Thread.sleep(millis);
844             else // too short to sleep
845                 Thread.yield();
846             nanos = wakeupTime - System.nanoTime();
847             millis = nanos / (1000 * 1000);
848         } while (nanos >= 0L);
849     }
850 
851     /**
852      * Allows use of try-with-resources with per-test thread pools.
853      */
854     class PoolCleaner implements AutoCloseable {
855         private final ExecutorService pool;
PoolCleaner(ExecutorService pool)856         public PoolCleaner(ExecutorService pool) { this.pool = pool; }
close()857         public void close() { joinPool(pool); }
858     }
859 
860     /**
861      * An extension of PoolCleaner that has an action to release the pool.
862      */
863     class PoolCleanerWithReleaser extends PoolCleaner {
864         private final Runnable releaser;
PoolCleanerWithReleaser(ExecutorService pool, Runnable releaser)865         public PoolCleanerWithReleaser(ExecutorService pool, Runnable releaser) {
866             super(pool);
867             this.releaser = releaser;
868         }
close()869         public void close() {
870             try {
871                 releaser.run();
872             } finally {
873                 super.close();
874             }
875         }
876     }
877 
cleaner(ExecutorService pool)878     PoolCleaner cleaner(ExecutorService pool) {
879         return new PoolCleaner(pool);
880     }
881 
cleaner(ExecutorService pool, Runnable releaser)882     PoolCleaner cleaner(ExecutorService pool, Runnable releaser) {
883         return new PoolCleanerWithReleaser(pool, releaser);
884     }
885 
cleaner(ExecutorService pool, CountDownLatch latch)886     PoolCleaner cleaner(ExecutorService pool, CountDownLatch latch) {
887         return new PoolCleanerWithReleaser(pool, releaser(latch));
888     }
889 
releaser(final CountDownLatch latch)890     Runnable releaser(final CountDownLatch latch) {
891         return new Runnable() { public void run() {
892             do { latch.countDown(); }
893             while (latch.getCount() > 0);
894         }};
895     }
896 
897     PoolCleaner cleaner(ExecutorService pool, AtomicBoolean flag) {
898         return new PoolCleanerWithReleaser(pool, releaser(flag));
899     }
900 
901     Runnable releaser(final AtomicBoolean flag) {
902         return new Runnable() { public void run() { flag.set(true); }};
903     }
904 
905     /**
906      * Waits out termination of a thread pool or fails doing so.
907      */
908     void joinPool(ExecutorService pool) {
909         try {
910             pool.shutdown();
911             if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS)) {
912                 try {
913                     threadFail("ExecutorService " + pool +
914                                " did not terminate in a timely manner");
915                 } finally {
916                     // last resort, for the benefit of subsequent tests
917                     pool.shutdownNow();
918                     pool.awaitTermination(MEDIUM_DELAY_MS, MILLISECONDS);
919                 }
920             }
921         } catch (SecurityException ok) {
922             // Allowed in case test doesn't have privs
923         } catch (InterruptedException fail) {
924             threadFail("Unexpected InterruptedException");
925         }
926     }
927 
928     /** Like Runnable, but with the freedom to throw anything */
929     interface Action { public void run() throws Throwable; }
930 
931     /**
932      * Runs all the given actions in parallel, failing if any fail.
933      * Useful for running multiple variants of tests that are
934      * necessarily individually slow because they must block.
935      */
936     void testInParallel(Action ... actions) {
937         ExecutorService pool = Executors.newCachedThreadPool();
938         try (PoolCleaner cleaner = cleaner(pool)) {
939             ArrayList<Future<?>> futures = new ArrayList<>(actions.length);
940             for (final Action action : actions)
941                 futures.add(pool.submit(new CheckedRunnable() {
942                     public void realRun() throws Throwable { action.run();}}));
943             for (Future<?> future : futures)
944                 try {
945                     assertNull(future.get(LONG_DELAY_MS, MILLISECONDS));
946                 } catch (ExecutionException ex) {
947                     threadUnexpectedException(ex.getCause());
948                 } catch (Exception ex) {
949                     threadUnexpectedException(ex);
950                 }
951         }
952     }
953 
954     /**
955      * A debugging tool to print stack traces of most threads, as jstack does.
956      * Uninteresting threads are filtered out.
957      */
958     static void dumpTestThreads() {
959         // Android-removed: no ThreadMXBean.
960         // ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
961         // System.err.println("------ stacktrace dump start ------");
962         // for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) {
963         //     String name = info.getThreadName();
964         //     if ("Signal Dispatcher".equals(name))
965         //         continue;
966         //     if ("Reference Handler".equals(name)
967         //         && info.getLockName().startsWith("java.lang.ref.Reference$Lock"))
968         //         continue;
969         //     if ("Finalizer".equals(name)
970         //         && info.getLockName().startsWith("java.lang.ref.ReferenceQueue$Lock"))
971         //         continue;
972         //     if ("checkForWedgedTest".equals(name))
973         //         continue;
974         //     System.err.print(info);
975         // }
976         // System.err.println("------ stacktrace dump end ------");
977     }
978 
979     /**
980      * Checks that thread does not terminate within the default
981      * millisecond delay of {@code timeoutMillis()}.
982      */
983     void assertThreadStaysAlive(Thread thread) {
984         assertThreadStaysAlive(thread, timeoutMillis());
985     }
986 
987     /**
988      * Checks that thread does not terminate within the given millisecond delay.
989      */
990     void assertThreadStaysAlive(Thread thread, long millis) {
991         try {
992             // No need to optimize the failing case via Thread.join.
993             delay(millis);
994             assertTrue(thread.isAlive());
995         } catch (InterruptedException fail) {
996             threadFail("Unexpected InterruptedException");
997         }
998     }
999 
1000     /**
1001      * Checks that the threads do not terminate within the default
1002      * millisecond delay of {@code timeoutMillis()}.
1003      */
1004     void assertThreadsStayAlive(Thread... threads) {
1005         assertThreadsStayAlive(timeoutMillis(), threads);
1006     }
1007 
1008     /**
1009      * Checks that the threads do not terminate within the given millisecond delay.
1010      */
1011     void assertThreadsStayAlive(long millis, Thread... threads) {
1012         try {
1013             // No need to optimize the failing case via Thread.join.
1014             delay(millis);
1015             for (Thread thread : threads)
1016                 assertTrue(thread.isAlive());
1017         } catch (InterruptedException fail) {
1018             threadFail("Unexpected InterruptedException");
1019         }
1020     }
1021 
1022     /**
1023      * Checks that future.get times out, with the default timeout of
1024      * {@code timeoutMillis()}.
1025      */
1026     void assertFutureTimesOut(Future future) {
1027         assertFutureTimesOut(future, timeoutMillis());
1028     }
1029 
1030     /**
1031      * Checks that future.get times out, with the given millisecond timeout.
1032      */
1033     void assertFutureTimesOut(Future future, long timeoutMillis) {
1034         long startTime = System.nanoTime();
1035         try {
1036             future.get(timeoutMillis, MILLISECONDS);
1037             shouldThrow();
1038         } catch (TimeoutException success) {
1039         } catch (Exception fail) {
1040             threadUnexpectedException(fail);
1041         } finally { future.cancel(true); }
1042         assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
1043     }
1044 
1045     /**
1046      * Fails with message "should throw exception".
1047      */
1048     public void shouldThrow() {
1049         fail("Should throw exception");
1050     }
1051 
1052     /**
1053      * Fails with message "should throw " + exceptionName.
1054      */
1055     public void shouldThrow(String exceptionName) {
1056         fail("Should throw " + exceptionName);
1057     }
1058 
1059     /**
1060      * The number of elements to place in collections, arrays, etc.
1061      */
1062     public static final int SIZE = 20;
1063 
1064     // Some convenient Integer constants
1065 
1066     public static final Integer zero  = new Integer(0);
1067     public static final Integer one   = new Integer(1);
1068     public static final Integer two   = new Integer(2);
1069     public static final Integer three = new Integer(3);
1070     public static final Integer four  = new Integer(4);
1071     public static final Integer five  = new Integer(5);
1072     public static final Integer six   = new Integer(6);
1073     public static final Integer seven = new Integer(7);
1074     public static final Integer eight = new Integer(8);
1075     public static final Integer nine  = new Integer(9);
1076     public static final Integer m1  = new Integer(-1);
1077     public static final Integer m2  = new Integer(-2);
1078     public static final Integer m3  = new Integer(-3);
1079     public static final Integer m4  = new Integer(-4);
1080     public static final Integer m5  = new Integer(-5);
1081     public static final Integer m6  = new Integer(-6);
1082     public static final Integer m10 = new Integer(-10);
1083 
1084     /**
1085      * Runs Runnable r with a security policy that permits precisely
1086      * the specified permissions.  If there is no current security
1087      * manager, the runnable is run twice, both with and without a
1088      * security manager.  We require that any security manager permit
1089      * getPolicy/setPolicy.
1090      */
1091     public void runWithPermissions(Runnable r, Permission... permissions) {
1092         // Android-removed: no SecurityManager.
1093         // SecurityManager sm = System.getSecurityManager();
1094         // if (sm == null) {
1095         //     r.run();
1096         // }
1097         // runWithSecurityManagerWithPermissions(r, permissions);
1098         r.run();
1099     }
1100 
1101     /**
1102      * Runs Runnable r with a security policy that permits precisely
1103      * the specified permissions.  If there is no current security
1104      * manager, a temporary one is set for the duration of the
1105      * Runnable.  We require that any security manager permit
1106      * getPolicy/setPolicy.
1107      */
1108     public void runWithSecurityManagerWithPermissions(Runnable r,
1109                                                       Permission... permissions) {
1110         // Android-removed: no SecurityManager.
1111         // SecurityManager sm = System.getSecurityManager();
1112         // if (sm == null) {
1113         //     Policy savedPolicy = Policy.getPolicy();
1114         //     try {
1115         //         Policy.setPolicy(permissivePolicy());
1116         //         System.setSecurityManager(new SecurityManager());
1117         //         runWithSecurityManagerWithPermissions(r, permissions);
1118         //     } finally {
1119         //         System.setSecurityManager(null);
1120         //         Policy.setPolicy(savedPolicy);
1121         //     }
1122         // } else {
1123         //     Policy savedPolicy = Policy.getPolicy();
1124         //     AdjustablePolicy policy = new AdjustablePolicy(permissions);
1125         //     Policy.setPolicy(policy);
1126 
1127         //     try {
1128         //         r.run();
1129         //     } finally {
1130         //         policy.addPermission(new SecurityPermission("setPolicy"));
1131         //         Policy.setPolicy(savedPolicy);
1132         //     }
1133         // }
1134         r.run();
1135     }
1136 
1137     /**
1138      * Runs a runnable without any permissions.
1139      */
1140     public void runWithoutPermissions(Runnable r) {
1141         runWithPermissions(r);
1142     }
1143 
1144     /**
1145      * A security policy where new permissions can be dynamically added
1146      * or all cleared.
1147      */
1148     public static class AdjustablePolicy extends java.security.Policy {
1149         Permissions perms = new Permissions();
1150         AdjustablePolicy(Permission... permissions) {
1151             for (Permission permission : permissions)
1152                 perms.add(permission);
1153         }
1154         void addPermission(Permission perm) { perms.add(perm); }
1155         void clearPermissions() { perms = new Permissions(); }
1156         public PermissionCollection getPermissions(CodeSource cs) {
1157             return perms;
1158         }
1159         public PermissionCollection getPermissions(ProtectionDomain pd) {
1160             return perms;
1161         }
1162         public boolean implies(ProtectionDomain pd, Permission p) {
1163             return perms.implies(p);
1164         }
1165         public void refresh() {}
1166         public String toString() {
1167             List<Permission> ps = new ArrayList<Permission>();
1168             for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
1169                 ps.add(e.nextElement());
1170             return "AdjustablePolicy with permissions " + ps;
1171         }
1172     }
1173 
1174     /**
1175      * Returns a policy containing all the permissions we ever need.
1176      */
1177     public static Policy permissivePolicy() {
1178         return new AdjustablePolicy
1179             // Permissions j.u.c. needs directly
1180             (new RuntimePermission("modifyThread"),
1181              new RuntimePermission("getClassLoader"),
1182              new RuntimePermission("setContextClassLoader"),
1183              // Permissions needed to change permissions!
1184              new SecurityPermission("getPolicy"),
1185              new SecurityPermission("setPolicy"),
1186              new RuntimePermission("setSecurityManager"),
1187              // Permissions needed by the junit test harness
1188              new RuntimePermission("accessDeclaredMembers"),
1189              new PropertyPermission("*", "read"),
1190              new java.io.FilePermission("<<ALL FILES>>", "read"));
1191     }
1192 
1193     /**
1194      * Sleeps until the given time has elapsed.
1195      * Throws AssertionFailedError if interrupted.
1196      */
1197     void sleep(long millis) {
1198         try {
1199             delay(millis);
1200         } catch (InterruptedException fail) {
1201             AssertionFailedError afe =
1202                 new AssertionFailedError("Unexpected InterruptedException");
1203             afe.initCause(fail);
1204             throw afe;
1205         }
1206     }
1207 
1208     /**
1209      * Spin-waits up to the specified number of milliseconds for the given
1210      * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1211      */
1212     void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
1213         long startTime = System.nanoTime();
1214         for (;;) {
1215             Thread.State s = thread.getState();
1216             if (s == Thread.State.BLOCKED ||
1217                 s == Thread.State.WAITING ||
1218                 s == Thread.State.TIMED_WAITING)
1219                 return;
1220             else if (s == Thread.State.TERMINATED)
1221                 fail("Unexpected thread termination");
1222             else if (millisElapsedSince(startTime) > timeoutMillis) {
1223                 threadAssertTrue(thread.isAlive());
1224                 fail("timed out waiting for thread to enter wait state");
1225             }
1226             Thread.yield();
1227         }
1228     }
1229 
1230     /**
1231      * Spin-waits up to the specified number of milliseconds for the given
1232      * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING,
1233      * and additionally satisfy the given condition.
1234      */
1235     void waitForThreadToEnterWaitState(
1236         Thread thread, long timeoutMillis, Callable<Boolean> waitingForGodot) {
1237         long startTime = 0L;
1238         for (;;) {
1239             Thread.State s = thread.getState();
1240             if (s == Thread.State.BLOCKED ||
1241                 s == Thread.State.WAITING ||
1242                 s == Thread.State.TIMED_WAITING) {
1243                 try {
1244                     if (waitingForGodot.call())
1245                         return;
1246                 } catch (Throwable fail) { threadUnexpectedException(fail); }
1247             }
1248             else if (s == Thread.State.TERMINATED)
1249                 fail("Unexpected thread termination");
1250             else if (startTime == 0L)
1251                 startTime = System.nanoTime();
1252             else if (millisElapsedSince(startTime) > timeoutMillis) {
1253                 threadAssertTrue(thread.isAlive());
1254                 fail("timed out waiting for thread to enter wait state");
1255             }
1256             Thread.yield();
1257         }
1258     }
1259 
1260     /**
1261      * Spin-waits up to LONG_DELAY_MS milliseconds for the given thread to
1262      * enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1263      */
1264     void waitForThreadToEnterWaitState(Thread thread) {
1265         waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
1266     }
1267 
1268     /**
1269      * Spin-waits up to LONG_DELAY_MS milliseconds for the given thread to
1270      * enter a wait state: BLOCKED, WAITING, or TIMED_WAITING,
1271      * and additionally satisfy the given condition.
1272      */
1273     void waitForThreadToEnterWaitState(
1274         Thread thread, Callable<Boolean> waitingForGodot) {
1275         waitForThreadToEnterWaitState(thread, LONG_DELAY_MS, waitingForGodot);
1276     }
1277 
1278     /**
1279      * Returns the number of milliseconds since time given by
1280      * startNanoTime, which must have been previously returned from a
1281      * call to {@link System#nanoTime()}.
1282      */
1283     static long millisElapsedSince(long startNanoTime) {
1284         return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
1285     }
1286 
1287 //     void assertTerminatesPromptly(long timeoutMillis, Runnable r) {
1288 //         long startTime = System.nanoTime();
1289 //         try {
1290 //             r.run();
1291 //         } catch (Throwable fail) { threadUnexpectedException(fail); }
1292 //         if (millisElapsedSince(startTime) > timeoutMillis/2)
1293 //             throw new AssertionFailedError("did not return promptly");
1294 //     }
1295 
1296 //     void assertTerminatesPromptly(Runnable r) {
1297 //         assertTerminatesPromptly(LONG_DELAY_MS/2, r);
1298 //     }
1299 
1300     /**
1301      * Checks that timed f.get() returns the expected value, and does not
1302      * wait for the timeout to elapse before returning.
1303      */
1304     <T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) {
1305         long startTime = System.nanoTime();
1306         try {
1307             assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
1308         } catch (Throwable fail) { threadUnexpectedException(fail); }
1309         if (millisElapsedSince(startTime) > timeoutMillis/2)
1310             throw new AssertionFailedError("timed get did not return promptly");
1311     }
1312 
1313     <T> void checkTimedGet(Future<T> f, T expectedValue) {
1314         checkTimedGet(f, expectedValue, LONG_DELAY_MS);
1315     }
1316 
1317     /**
1318      * Returns a new started daemon Thread running the given runnable.
1319      */
1320     Thread newStartedThread(Runnable runnable) {
1321         Thread t = new Thread(runnable);
1322         t.setDaemon(true);
1323         t.start();
1324         return t;
1325     }
1326 
1327     /**
1328      * Waits for the specified time (in milliseconds) for the thread
1329      * to terminate (using {@link Thread#join(long)}), else interrupts
1330      * the thread (in the hope that it may terminate later) and fails.
1331      */
1332     void awaitTermination(Thread t, long timeoutMillis) {
1333         try {
1334             t.join(timeoutMillis);
1335         } catch (InterruptedException fail) {
1336             threadUnexpectedException(fail);
1337         } finally {
1338             if (t.getState() != Thread.State.TERMINATED) {
1339                 t.interrupt();
1340                 threadFail("timed out waiting for thread to terminate");
1341             }
1342         }
1343     }
1344 
1345     /**
1346      * Waits for LONG_DELAY_MS milliseconds for the thread to
1347      * terminate (using {@link Thread#join(long)}), else interrupts
1348      * the thread (in the hope that it may terminate later) and fails.
1349      */
1350     void awaitTermination(Thread t) {
1351         awaitTermination(t, LONG_DELAY_MS);
1352     }
1353 
1354     // Some convenient Runnable classes
1355 
1356     public abstract class CheckedRunnable implements Runnable {
1357         protected abstract void realRun() throws Throwable;
1358 
1359         public final void run() {
1360             try {
1361                 realRun();
1362             } catch (Throwable fail) {
1363                 threadUnexpectedException(fail);
1364             }
1365         }
1366     }
1367 
1368     public abstract class RunnableShouldThrow implements Runnable {
1369         protected abstract void realRun() throws Throwable;
1370 
1371         final Class<?> exceptionClass;
1372 
1373         <T extends Throwable> RunnableShouldThrow(Class<T> exceptionClass) {
1374             this.exceptionClass = exceptionClass;
1375         }
1376 
1377         public final void run() {
1378             try {
1379                 realRun();
1380                 threadShouldThrow(exceptionClass.getSimpleName());
1381             } catch (Throwable t) {
1382                 if (! exceptionClass.isInstance(t))
1383                     threadUnexpectedException(t);
1384             }
1385         }
1386     }
1387 
1388     public abstract class ThreadShouldThrow extends Thread {
1389         protected abstract void realRun() throws Throwable;
1390 
1391         final Class<?> exceptionClass;
1392 
1393         <T extends Throwable> ThreadShouldThrow(Class<T> exceptionClass) {
1394             this.exceptionClass = exceptionClass;
1395         }
1396 
1397         public final void run() {
1398             try {
1399                 realRun();
1400                 threadShouldThrow(exceptionClass.getSimpleName());
1401             } catch (Throwable t) {
1402                 if (! exceptionClass.isInstance(t))
1403                     threadUnexpectedException(t);
1404             }
1405         }
1406     }
1407 
1408     public abstract class CheckedInterruptedRunnable implements Runnable {
1409         protected abstract void realRun() throws Throwable;
1410 
1411         public final void run() {
1412             try {
1413                 realRun();
1414                 threadShouldThrow("InterruptedException");
1415             } catch (InterruptedException success) {
1416                 threadAssertFalse(Thread.interrupted());
1417             } catch (Throwable fail) {
1418                 threadUnexpectedException(fail);
1419             }
1420         }
1421     }
1422 
1423     public abstract class CheckedCallable<T> implements Callable<T> {
1424         protected abstract T realCall() throws Throwable;
1425 
1426         public final T call() {
1427             try {
1428                 return realCall();
1429             } catch (Throwable fail) {
1430                 threadUnexpectedException(fail);
1431                 return null;
1432             }
1433         }
1434     }
1435 
1436     public abstract class CheckedInterruptedCallable<T>
1437         implements Callable<T> {
1438         protected abstract T realCall() throws Throwable;
1439 
1440         public final T call() {
1441             try {
1442                 T result = realCall();
1443                 threadShouldThrow("InterruptedException");
1444                 return result;
1445             } catch (InterruptedException success) {
1446                 threadAssertFalse(Thread.interrupted());
1447             } catch (Throwable fail) {
1448                 threadUnexpectedException(fail);
1449             }
1450             return null;
1451         }
1452     }
1453 
1454     public static class NoOpRunnable implements Runnable {
1455         public void run() {}
1456     }
1457 
1458     public static class NoOpCallable implements Callable {
1459         public Object call() { return Boolean.TRUE; }
1460     }
1461 
1462     public static final String TEST_STRING = "a test string";
1463 
1464     public static class StringTask implements Callable<String> {
1465         final String value;
1466         public StringTask() { this(TEST_STRING); }
1467         public StringTask(String value) { this.value = value; }
1468         public String call() { return value; }
1469     }
1470 
1471     public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
1472         return new CheckedCallable<String>() {
1473             protected String realCall() {
1474                 try {
1475                     latch.await();
1476                 } catch (InterruptedException quittingTime) {}
1477                 return TEST_STRING;
1478             }};
1479     }
1480 
1481     public Runnable countDowner(final CountDownLatch latch) {
1482         return new CheckedRunnable() {
1483             public void realRun() throws InterruptedException {
1484                 latch.countDown();
1485             }};
1486     }
1487 
1488     class LatchAwaiter extends CheckedRunnable {
1489         static final int NEW = 0;
1490         static final int RUNNING = 1;
1491         static final int DONE = 2;
1492         final CountDownLatch latch;
1493         int state = NEW;
1494         LatchAwaiter(CountDownLatch latch) { this.latch = latch; }
1495         public void realRun() throws InterruptedException {
1496             state = 1;
1497             await(latch);
1498             state = 2;
1499         }
1500     }
1501 
1502     public LatchAwaiter awaiter(CountDownLatch latch) {
1503         return new LatchAwaiter(latch);
1504     }
1505 
1506     public void await(CountDownLatch latch, long timeoutMillis) {
1507         try {
1508             if (!latch.await(timeoutMillis, MILLISECONDS))
1509                 fail("timed out waiting for CountDownLatch for "
1510                      + (timeoutMillis/1000) + " sec");
1511         } catch (Throwable fail) {
1512             threadUnexpectedException(fail);
1513         }
1514     }
1515 
1516     public void await(CountDownLatch latch) {
1517         await(latch, LONG_DELAY_MS);
1518     }
1519 
1520     public void await(Semaphore semaphore) {
1521         try {
1522             if (!semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS))
1523                 fail("timed out waiting for Semaphore for "
1524                      + (LONG_DELAY_MS/1000) + " sec");
1525         } catch (Throwable fail) {
1526             threadUnexpectedException(fail);
1527         }
1528     }
1529 
1530 //     /**
1531 //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1532 //      */
1533 //     public void await(AtomicBoolean flag) {
1534 //         await(flag, LONG_DELAY_MS);
1535 //     }
1536 
1537 //     /**
1538 //      * Spin-waits up to the specified timeout until flag becomes true.
1539 //      */
1540 //     public void await(AtomicBoolean flag, long timeoutMillis) {
1541 //         long startTime = System.nanoTime();
1542 //         while (!flag.get()) {
1543 //             if (millisElapsedSince(startTime) > timeoutMillis)
1544 //                 throw new AssertionFailedError("timed out");
1545 //             Thread.yield();
1546 //         }
1547 //     }
1548 
1549     public static class NPETask implements Callable<String> {
1550         public String call() { throw new NullPointerException(); }
1551     }
1552 
1553     public static class CallableOne implements Callable<Integer> {
1554         public Integer call() { return one; }
1555     }
1556 
1557     public class ShortRunnable extends CheckedRunnable {
1558         protected void realRun() throws Throwable {
1559             delay(SHORT_DELAY_MS);
1560         }
1561     }
1562 
1563     public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1564         protected void realRun() throws InterruptedException {
1565             delay(SHORT_DELAY_MS);
1566         }
1567     }
1568 
1569     public class SmallRunnable extends CheckedRunnable {
1570         protected void realRun() throws Throwable {
1571             delay(SMALL_DELAY_MS);
1572         }
1573     }
1574 
1575     public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1576         protected void realRun() {
1577             try {
1578                 delay(SMALL_DELAY_MS);
1579             } catch (InterruptedException ok) {}
1580         }
1581     }
1582 
1583     public class SmallCallable extends CheckedCallable {
1584         protected Object realCall() throws InterruptedException {
1585             delay(SMALL_DELAY_MS);
1586             return Boolean.TRUE;
1587         }
1588     }
1589 
1590     public class MediumRunnable extends CheckedRunnable {
1591         protected void realRun() throws Throwable {
1592             delay(MEDIUM_DELAY_MS);
1593         }
1594     }
1595 
1596     public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1597         protected void realRun() throws InterruptedException {
1598             delay(MEDIUM_DELAY_MS);
1599         }
1600     }
1601 
1602     public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1603         return new CheckedRunnable() {
1604             protected void realRun() {
1605                 try {
1606                     delay(timeoutMillis);
1607                 } catch (InterruptedException ok) {}
1608             }};
1609     }
1610 
1611     public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1612         protected void realRun() {
1613             try {
1614                 delay(MEDIUM_DELAY_MS);
1615             } catch (InterruptedException ok) {}
1616         }
1617     }
1618 
1619     public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1620         protected void realRun() {
1621             try {
1622                 delay(LONG_DELAY_MS);
1623             } catch (InterruptedException ok) {}
1624         }
1625     }
1626 
1627     /**
1628      * For use as ThreadFactory in constructors
1629      */
1630     public static class SimpleThreadFactory implements ThreadFactory {
1631         public Thread newThread(Runnable r) {
1632             return new Thread(r);
1633         }
1634     }
1635 
1636     public interface TrackedRunnable extends Runnable {
1637         boolean isDone();
1638     }
1639 
1640     public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
1641         return new TrackedRunnable() {
1642                 private volatile boolean done = false;
1643                 public boolean isDone() { return done; }
1644                 public void run() {
1645                     try {
1646                         delay(timeoutMillis);
1647                         done = true;
1648                     } catch (InterruptedException ok) {}
1649                 }
1650             };
1651     }
1652 
1653     public static class TrackedShortRunnable implements Runnable {
1654         public volatile boolean done = false;
1655         public void run() {
1656             try {
1657                 delay(SHORT_DELAY_MS);
1658                 done = true;
1659             } catch (InterruptedException ok) {}
1660         }
1661     }
1662 
1663     public static class TrackedSmallRunnable implements Runnable {
1664         public volatile boolean done = false;
1665         public void run() {
1666             try {
1667                 delay(SMALL_DELAY_MS);
1668                 done = true;
1669             } catch (InterruptedException ok) {}
1670         }
1671     }
1672 
1673     public static class TrackedMediumRunnable implements Runnable {
1674         public volatile boolean done = false;
1675         public void run() {
1676             try {
1677                 delay(MEDIUM_DELAY_MS);
1678                 done = true;
1679             } catch (InterruptedException ok) {}
1680         }
1681     }
1682 
1683     public static class TrackedLongRunnable implements Runnable {
1684         public volatile boolean done = false;
1685         public void run() {
1686             try {
1687                 delay(LONG_DELAY_MS);
1688                 done = true;
1689             } catch (InterruptedException ok) {}
1690         }
1691     }
1692 
1693     public static class TrackedNoOpRunnable implements Runnable {
1694         public volatile boolean done = false;
1695         public void run() {
1696             done = true;
1697         }
1698     }
1699 
1700     public static class TrackedCallable implements Callable {
1701         public volatile boolean done = false;
1702         public Object call() {
1703             try {
1704                 delay(SMALL_DELAY_MS);
1705                 done = true;
1706             } catch (InterruptedException ok) {}
1707             return Boolean.TRUE;
1708         }
1709     }
1710 
1711     /**
1712      * Analog of CheckedRunnable for RecursiveAction
1713      */
1714     public abstract class CheckedRecursiveAction extends RecursiveAction {
1715         protected abstract void realCompute() throws Throwable;
1716 
1717         @Override protected final void compute() {
1718             try {
1719                 realCompute();
1720             } catch (Throwable fail) {
1721                 threadUnexpectedException(fail);
1722             }
1723         }
1724     }
1725 
1726     /**
1727      * Analog of CheckedCallable for RecursiveTask
1728      */
1729     public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1730         protected abstract T realCompute() throws Throwable;
1731 
1732         @Override protected final T compute() {
1733             try {
1734                 return realCompute();
1735             } catch (Throwable fail) {
1736                 threadUnexpectedException(fail);
1737                 return null;
1738             }
1739         }
1740     }
1741 
1742     /**
1743      * For use as RejectedExecutionHandler in constructors
1744      */
1745     public static class NoOpREHandler implements RejectedExecutionHandler {
1746         public void rejectedExecution(Runnable r,
1747                                       ThreadPoolExecutor executor) {}
1748     }
1749 
1750     /**
1751      * A CyclicBarrier that uses timed await and fails with
1752      * AssertionFailedErrors instead of throwing checked exceptions.
1753      */
1754     public class CheckedBarrier extends CyclicBarrier {
1755         public CheckedBarrier(int parties) { super(parties); }
1756 
1757         public int await() {
1758             try {
1759                 return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1760             } catch (TimeoutException timedOut) {
1761                 throw new AssertionFailedError("timed out");
1762             } catch (Exception fail) {
1763                 AssertionFailedError afe =
1764                     new AssertionFailedError("Unexpected exception: " + fail);
1765                 afe.initCause(fail);
1766                 throw afe;
1767             }
1768         }
1769     }
1770 
1771     void checkEmpty(BlockingQueue q) {
1772         try {
1773             assertTrue(q.isEmpty());
1774             assertEquals(0, q.size());
1775             assertNull(q.peek());
1776             assertNull(q.poll());
1777             assertNull(q.poll(0, MILLISECONDS));
1778             assertEquals(q.toString(), "[]");
1779             assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1780             assertFalse(q.iterator().hasNext());
1781             try {
1782                 q.element();
1783                 shouldThrow();
1784             } catch (NoSuchElementException success) {}
1785             try {
1786                 q.iterator().next();
1787                 shouldThrow();
1788             } catch (NoSuchElementException success) {}
1789             try {
1790                 q.remove();
1791                 shouldThrow();
1792             } catch (NoSuchElementException success) {}
1793         } catch (InterruptedException fail) { threadUnexpectedException(fail); }
1794     }
1795 
1796     void assertSerialEquals(Object x, Object y) {
1797         assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1798     }
1799 
1800     void assertNotSerialEquals(Object x, Object y) {
1801         assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1802     }
1803 
1804     byte[] serialBytes(Object o) {
1805         try {
1806             ByteArrayOutputStream bos = new ByteArrayOutputStream();
1807             ObjectOutputStream oos = new ObjectOutputStream(bos);
1808             oos.writeObject(o);
1809             oos.flush();
1810             oos.close();
1811             return bos.toByteArray();
1812         } catch (Throwable fail) {
1813             threadUnexpectedException(fail);
1814             return new byte[0];
1815         }
1816     }
1817 
1818     @SuppressWarnings("unchecked")
1819     <T> T serialClone(T o) {
1820         try {
1821             ObjectInputStream ois = new ObjectInputStream
1822                 (new ByteArrayInputStream(serialBytes(o)));
1823             T clone = (T) ois.readObject();
1824             assertSame(o.getClass(), clone.getClass());
1825             return clone;
1826         } catch (Throwable fail) {
1827             threadUnexpectedException(fail);
1828             return null;
1829         }
1830     }
1831 
1832     public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1833                              Runnable... throwingActions) {
1834         for (Runnable throwingAction : throwingActions) {
1835             boolean threw = false;
1836             try { throwingAction.run(); }
1837             catch (Throwable t) {
1838                 threw = true;
1839                 if (!expectedExceptionClass.isInstance(t)) {
1840                     AssertionFailedError afe =
1841                         new AssertionFailedError
1842                         ("Expected " + expectedExceptionClass.getName() +
1843                          ", got " + t.getClass().getName());
1844                     afe.initCause(t);
1845                     threadUnexpectedException(afe);
1846                 }
1847             }
1848             if (!threw)
1849                 shouldThrow(expectedExceptionClass.getName());
1850         }
1851     }
1852 
1853     public void assertIteratorExhausted(Iterator<?> it) {
1854         try {
1855             it.next();
1856             shouldThrow();
1857         } catch (NoSuchElementException success) {}
1858         assertFalse(it.hasNext());
1859     }
1860 }
1861