• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
3  *
4  * This code is free software; you can redistribute it and/or modify it
5  * under the terms of the GNU General Public License version 2 only, as
6  * published by the Free Software Foundation.
7  *
8  * This code is distributed in the hope that it will be useful, but WITHOUT
9  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
11  * version 2 for more details (a copy is included in the LICENSE file that
12  * accompanied this code).
13  *
14  * You should have received a copy of the GNU General Public License version
15  * 2 along with this work; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
17  *
18  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
19  * or visit www.oracle.com if you need additional information or have any
20  * questions.
21  */
22 
23 /*
24  * This file is available under and governed by the GNU General Public
25  * License version 2 only, as published by the Free Software Foundation.
26  * However, the following notice accompanied the original version of this
27  * file:
28  *
29  * Written by Doug Lea with assistance from members of JCP JSR-166
30  * Expert Group and released to the public domain, as explained at
31  * http://creativecommons.org/publicdomain/zero/1.0/
32  * Other contributors include Andrew Wright, Jeffrey Hayes,
33  * Pat Fisher, Mike Judd.
34  */
35 
36 /*
37  * @test
38  * @summary JSR-166 tck tests (conformance testing mode)
39  * @build *
40  * @modules java.management
41  * @run junit/othervm/timeout=1000 JSR166TestCase
42  */
43 
44 /*
45  * @test
46  * @summary JSR-166 tck tests (whitebox tests allowed)
47  * @build *
48  * @modules java.base/java.util.concurrent:open
49  *          java.base/java.lang:open
50  *          java.management
51  * @run junit/othervm/timeout=1000
52  *      -Djsr166.testImplementationDetails=true
53  *      JSR166TestCase
54  * @run junit/othervm/timeout=1000
55  *      -Djsr166.testImplementationDetails=true
56  *      -Djava.util.concurrent.ForkJoinPool.common.parallelism=0
57  *      JSR166TestCase
58  * @run junit/othervm/timeout=1000
59  *      -Djsr166.testImplementationDetails=true
60  *      -Djava.util.concurrent.ForkJoinPool.common.parallelism=1
61  *      -Djava.util.secureRandomSeed=true
62  *      JSR166TestCase
63  * @run junit/othervm/timeout=1000/policy=tck.policy
64  *      -Djsr166.testImplementationDetails=true
65  *      JSR166TestCase
66  */
67 
68 package test.java.util.concurrent.tck;
69 import static java.util.concurrent.TimeUnit.MILLISECONDS;
70 import static java.util.concurrent.TimeUnit.MINUTES;
71 import static java.util.concurrent.TimeUnit.NANOSECONDS;
72 import static org.junit.Assert.assertEquals;
73 import static org.junit.Assert.assertFalse;
74 import static org.junit.Assert.assertNotSame;
75 import static org.junit.Assert.assertNull;
76 import static org.junit.Assert.assertNotNull;
77 import static org.junit.Assert.assertSame;
78 import static org.junit.Assert.assertNotSame;
79 import static org.junit.Assert.assertTrue;
80 import static org.junit.Assert.fail;
81 
82 import java.io.ByteArrayInputStream;
83 import java.io.ByteArrayOutputStream;
84 import java.io.ObjectInputStream;
85 import java.io.ObjectOutputStream;
86 //import java.lang.management.ManagementFactory;
87 //import java.lang.management.ThreadInfo;
88 //import java.lang.management.ThreadMXBean;
89 import java.lang.reflect.Constructor;
90 import java.lang.reflect.Method;
91 import java.lang.reflect.Modifier;
92 import java.nio.file.Files;
93 import java.nio.file.Paths;
94 import java.security.CodeSource;
95 import java.security.Permission;
96 import java.security.PermissionCollection;
97 import java.security.Permissions;
98 import java.security.Policy;
99 import java.security.ProtectionDomain;
100 import java.security.SecurityPermission;
101 import java.util.ArrayList;
102 import java.util.Arrays;
103 import java.util.Collection;
104 import java.util.Collections;
105 import java.util.Date;
106 import java.util.Enumeration;
107 import java.util.Iterator;
108 import java.util.List;
109 import java.util.NoSuchElementException;
110 import java.util.PropertyPermission;
111 import java.util.concurrent.BlockingQueue;
112 import java.util.concurrent.Callable;
113 import java.util.concurrent.CountDownLatch;
114 import java.util.concurrent.CyclicBarrier;
115 import java.util.concurrent.ExecutionException;
116 import java.util.concurrent.Executors;
117 import java.util.concurrent.ExecutorService;
118 import java.util.concurrent.ForkJoinPool;
119 import java.util.concurrent.Future;
120 import java.util.concurrent.RecursiveAction;
121 import java.util.concurrent.RecursiveTask;
122 import java.util.concurrent.RejectedExecutionHandler;
123 import java.util.concurrent.Semaphore;
124 import java.util.concurrent.SynchronousQueue;
125 import java.util.concurrent.ThreadFactory;
126 import java.util.concurrent.ThreadLocalRandom;
127 import java.util.concurrent.ThreadPoolExecutor;
128 import java.util.concurrent.TimeUnit;
129 import java.util.concurrent.TimeoutException;
130 import java.util.concurrent.atomic.AtomicBoolean;
131 import java.util.concurrent.atomic.AtomicReference;
132 import java.util.regex.Matcher;
133 import java.util.regex.Pattern;
134 
135 import org.junit.After;
136 import org.junit.Assert;
137 import org.junit.Before;
138 import org.junit.runner.RunWith;
139 import org.junit.runners.Suite;
140 import org.junit.runners.Suite.SuiteClasses;
141 
142 /**
143  * Base class for JSR166 Junit TCK tests.  Defines some constants,
144  * utility methods and classes, as well as a simple framework for
145  * helping to make sure that assertions failing in generated threads
146  * cause the associated test that generated them to itself fail (which
147  * JUnit does not otherwise arrange).  The rules for creating such
148  * tests are:
149  *
150  * <ol>
151  *
152  * <li>All assertions in code running in generated threads must use
153  * the forms {@link #threadFail}, {@link #threadAssertTrue}, {@link
154  * #threadAssertEquals}, or {@link #threadAssertNull}, (not
155  * {@code fail}, {@code assertTrue}, etc.) It is OK (but not
156  * particularly recommended) for other code to use these forms too.
157  * Only the most typically used JUnit assertion methods are defined
158  * this way, but enough to live with.
159  *
160  * <li>If you override {@link #setUp} or {@link #tearDown}, make sure
161  * to invoke {@code super.setUp} and {@code super.tearDown} within
162  * them. These methods are used to clear and check for thread
163  * assertion failures.
164  *
165  * <li>All delays and timeouts must use one of the constants {@code
166  * SHORT_DELAY_MS}, {@code SMALL_DELAY_MS}, {@code MEDIUM_DELAY_MS},
167  * {@code LONG_DELAY_MS}. The idea here is that a SHORT is always
168  * discriminable from zero time, and always allows enough time for the
169  * small amounts of computation (creating a thread, calling a few
170  * methods, etc) needed to reach a timeout point. Similarly, a SMALL
171  * is always discriminable as larger than SHORT and smaller than
172  * MEDIUM.  And so on. These constants are set to conservative values,
173  * but even so, if there is ever any doubt, they can all be increased
174  * in one spot to rerun tests on slower platforms.
175  *
176  * <li>All threads generated must be joined inside each test case
177  * method (or {@code fail} to do so) before returning from the
178  * method. The {@code joinPool} method can be used to do this when
179  * using Executors.
180  *
181  * </ol>
182  *
183  * <p><b>Other notes</b>
184  * <ul>
185  *
186  * <li>Usually, there is one testcase method per JSR166 method
187  * covering "normal" operation, and then as many exception-testing
188  * methods as there are exceptions the method can throw. Sometimes
189  * there are multiple tests per JSR166 method when the different
190  * "normal" behaviors differ significantly. And sometimes testcases
191  * cover multiple methods when they cannot be tested in isolation.
192  *
193  * <li>The documentation style for testcases is to provide as javadoc
194  * a simple sentence or two describing the property that the testcase
195  * method purports to test. The javadocs do not say anything about how
196  * the property is tested. To find out, read the code.
197  *
198  * <li>These tests are "conformance tests", and do not attempt to
199  * test throughput, latency, scalability or other performance factors
200  * (see the separate "jtreg" tests for a set intended to check these
201  * for the most central aspects of functionality.) So, most tests use
202  * the smallest sensible numbers of threads, collection sizes, etc
203  * needed to check basic conformance.
204  *
205  * <li>The test classes currently do not declare inclusion in
206  * any particular package to simplify things for people integrating
207  * them in TCK test suites.
208  *
209  * <li>As a convenience, the {@code main} of this class (JSR166TestCase)
210  * runs all JSR166 unit tests.
211  *
212  * </ul>
213  */
214 // Android-changed: Use JUnit4.
215 @RunWith(Suite.class)
216 @SuiteClasses({
217     ForkJoinPoolTest.class,
218     ForkJoinTaskTest.class,
219     RecursiveActionTest.class,
220     RecursiveTaskTest.class,
221     LinkedTransferQueueTest.class,
222     LinkedTransferQueueTest.Generic.class,
223     PhaserTest.class,
224     ThreadLocalRandomTest.class,
225     AbstractExecutorServiceTest.class,
226     AbstractQueueTest.class,
227     AbstractQueuedSynchronizerTest.class,
228     AbstractQueuedLongSynchronizerTest.class,
229     ArrayBlockingQueueTest.class,
230     ArrayBlockingQueueTest.Fair.class,
231     ArrayBlockingQueueTest.NonFair.class,
232     ArrayDequeTest.class,
233     // ArrayListTest.class,
234     AtomicBooleanTest.class,
235     AtomicIntegerArrayTest.class,
236     AtomicIntegerFieldUpdaterTest.class,
237     AtomicIntegerTest.class,
238     AtomicLongArrayTest.class,
239     AtomicLongFieldUpdaterTest.class,
240     AtomicLongTest.class,
241     AtomicMarkableReferenceTest.class,
242     AtomicReferenceArrayTest.class,
243     AtomicReferenceFieldUpdaterTest.class,
244     AtomicReferenceTest.class,
245     AtomicStampedReferenceTest.class,
246     ConcurrentHashMapTest.class,
247     ConcurrentLinkedDequeTest.class,
248     ConcurrentLinkedQueueTest.class,
249     ConcurrentSkipListMapTest.class,
250     ConcurrentSkipListSubMapTest.class,
251     ConcurrentSkipListSetTest.class,
252     ConcurrentSkipListSubSetTest.class,
253     CopyOnWriteArrayListTest.class,
254     CopyOnWriteArraySetTest.class,
255     CountDownLatchTest.class,
256     CountedCompleterTest.class,
257     CyclicBarrierTest.class,
258     DelayQueueTest.class,
259     DelayQueueTest.Generic.class,
260     EntryTest.class,
261     ExchangerTest.class,
262     ExecutorsTest.class,
263     ExecutorCompletionServiceTest.class,
264     FutureTaskTest.class,
265     LinkedBlockingDequeTest.class,
266     LinkedBlockingDequeTest.Unbounded.class,
267     LinkedBlockingDequeTest.Bounded.class,
268     LinkedBlockingQueueTest.class,
269     LinkedBlockingQueueTest.Unbounded.class,
270     LinkedBlockingQueueTest.Bounded.class,
271     LinkedListTest.class,
272     LockSupportTest.class,
273     PriorityBlockingQueueTest.class,
274     PriorityBlockingQueueTest.Generic.class,
275     PriorityBlockingQueueTest.InitialCapacity.class,
276     PriorityQueueTest.class,
277     ReentrantLockTest.class,
278     ReentrantReadWriteLockTest.class,
279     ScheduledExecutorTest.class,
280     ScheduledExecutorSubclassTest.class,
281     SemaphoreTest.class,
282     SynchronousQueueTest.class,
283     SynchronousQueueTest.Fair.class,
284     SynchronousQueueTest.NonFair.class,
285     SystemTest.class,
286     ThreadLocalTest.class,
287     ThreadPoolExecutorTest.class,
288     ThreadPoolExecutorSubclassTest.class,
289     ThreadTest.class,
290     TimeUnitTest.class,
291     TreeMapTest.class,
292     TreeSetTest.class,
293     TreeSubMapTest.class,
294     TreeSubSetTest.class,
295     VectorTest.class,
296     ArrayDeque8Test.class,
297     Atomic8Test.class,
298     CompletableFutureTest.class,
299     ConcurrentHashMap8Test.class,
300     CountedCompleter8Test.class,
301     DoubleAccumulatorTest.class,
302     DoubleAdderTest.class,
303     ForkJoinPool8Test.class,
304     ForkJoinPool19Test.class,
305     ForkJoinPool20Test.class,
306     ForkJoinTask8Test.class,
307     LinkedBlockingDeque8Test.class,
308     LinkedBlockingQueue8Test.class,
309     LongAccumulatorTest.class,
310     LongAdderTest.class,
311     SplittableRandomTest.class,
312     StampedLockTest.class,
313     SubmissionPublisherTest.class,
314     ThreadLocalRandom8Test.class,
315     TimeUnit8Test.class,
316     // AtomicBoolean9Test.class,
317     // AtomicInteger9Test.class,
318     // AtomicIntegerArray9Test.class,
319     // AtomicLong9Test.class,
320     // AtomicLongArray9Test.class,
321     // AtomicReference9Test.class,
322     // AtomicReferenceArray9Test.class,
323     // ExecutorCompletionService9Test.class,
324     // ForkJoinPool9Test.class,
325     SubmissionPublisherTest.class,
326 })
327 public class JSR166TestCase {
328     private static final boolean useSecurityManager =
329         Boolean.getBoolean("jsr166.useSecurityManager");
330 
331     protected static final boolean expensiveTests =
332         Boolean.getBoolean("jsr166.expensiveTests");
333 
334     /**
335      * If true, also run tests that are not part of the official tck
336      * because they test unspecified implementation details.
337      */
338     protected static final boolean testImplementationDetails =
339         Boolean.getBoolean("jsr166.testImplementationDetails");
340 
341     /**
342      * If true, report on stdout all "slow" tests, that is, ones that
343      * take more than profileThreshold milliseconds to execute.
344      */
345     private static final boolean profileTests =
346         Boolean.getBoolean("jsr166.profileTests");
347 
348     /**
349      * The number of milliseconds that tests are permitted for
350      * execution without being reported, when profileTests is set.
351      */
352     private static final long profileThreshold =
353         Long.getLong("jsr166.profileThreshold", 100);
354 
355     /**
356      * The number of repetitions per test (for tickling rare bugs).
357      */
358     private static final int runsPerTest =
359         Integer.getInteger("jsr166.runsPerTest", 1);
360 
361     /**
362      * The number of repetitions of the test suite (for finding leaks?).
363      */
364     private static final int suiteRuns =
365         Integer.getInteger("jsr166.suiteRuns", 1);
366 
367     /**
368      * Returns the value of the system property, or NaN if not defined.
369      */
systemPropertyValue(String name)370     private static float systemPropertyValue(String name) {
371         String floatString = System.getProperty(name);
372         if (floatString == null)
373             return Float.NaN;
374         try {
375             return Float.parseFloat(floatString);
376         } catch (NumberFormatException ex) {
377             throw new IllegalArgumentException(
378                 String.format("Bad float value in system property %s=%s",
379                               name, floatString));
380         }
381     }
382 
383     /**
384      * The scaling factor to apply to standard delays used in tests.
385      * May be initialized from any of:
386      * - the "jsr166.delay.factor" system property
387      * - the "test.timeout.factor" system property (as used by jtreg)
388      *   See: http://openjdk.java.net/jtreg/tag-spec.html
389      * - hard-coded fuzz factor when using a known slowpoke VM
390      */
391     private static final float delayFactor = delayFactor();
392 
delayFactor()393     private static float delayFactor() {
394         float x;
395         if (!Float.isNaN(x = systemPropertyValue("jsr166.delay.factor")))
396             return x;
397         if (!Float.isNaN(x = systemPropertyValue("test.timeout.factor")))
398             return x;
399         String prop = System.getProperty("java.vm.version");
400         if (prop != null && prop.matches(".*debug.*"))
401             return 4.0f; // How much slower is fastdebug than product?!
402         return 1.0f;
403     }
404 
405     /**
406      * A filter for tests to run, matching strings of the form
407      * methodName(className), e.g. "testInvokeAll5(ForkJoinPoolTest)"
408      * Usefully combined with jsr166.runsPerTest.
409      */
410     private static final Pattern methodFilter = methodFilter();
411 
methodFilter()412     private static Pattern methodFilter() {
413         String regex = System.getProperty("jsr166.methodFilter");
414         return (regex == null) ? null : Pattern.compile(regex);
415     }
416 
417     // BEGIN Android-removed: Usage of TestCase.
418     /*
419     // Instrumentation to debug very rare, but very annoying hung test runs.
420     static volatile TestCase currentTestCase;
421     // static volatile int currentRun = 0;
422     static {
423         Runnable checkForWedgedTest = new Runnable() { public void run() {
424             // Avoid spurious reports with enormous runsPerTest.
425             // A single test case run should never take more than 1 second.
426             // But let's cap it at the high end too ...
427             final int timeoutMinutes =
428                 Math.min(15, Math.max(runsPerTest / 60, 1));
429             for (TestCase lastTestCase = currentTestCase;;) {
430                 try { MINUTES.sleep(timeoutMinutes); }
431                 catch (InterruptedException unexpected) { break; }
432                 if (lastTestCase == currentTestCase) {
433                     System.err.printf(
434                         "Looks like we're stuck running test: %s%n",
435                         lastTestCase);
436 //                     System.err.printf(
437 //                         "Looks like we're stuck running test: %s (%d/%d)%n",
438 //                         lastTestCase, currentRun, runsPerTest);
439 //                     System.err.println("availableProcessors=" +
440 //                         Runtime.getRuntime().availableProcessors());
441 //                     System.err.printf("cpu model = %s%n", cpuModel());
442                     dumpTestThreads();
443                     // one stack dump is probably enough; more would be spam
444                     break;
445                 }
446                 lastTestCase = currentTestCase;
447             }}};
448         Thread thread = new Thread(checkForWedgedTest, "checkForWedgedTest");
449         thread.setDaemon(true);
450         thread.start();
451     }
452      */
453     // END Android-removed: Usage of TestCase.
454 
455 //     public static String cpuModel() {
456 //         try {
457 //             Matcher matcher = Pattern.compile("model name\\s*: (.*)")
458 //                 .matcher(new String(
459 //                      Files.readAllBytes(Paths.get("/proc/cpuinfo")), "UTF-8"));
460 //             matcher.find();
461 //             return matcher.group(1);
462 //         } catch (Exception ex) { return null; }
463 //     }
464 
465     // BEGIN Android-removed: Not used for JUnit4.
466     /*
467     public void runBare() throws Throwable {
468         currentTestCase = this;
469         if (methodFilter == null
470             || methodFilter.matcher(toString()).find())
471             super.runBare();
472     }
473 
474     protected void runTest() throws Throwable {
475         for (int i = 0; i < runsPerTest; i++) {
476             // currentRun = i;
477             if (profileTests)
478                 runTestProfiled();
479             else
480                 super.runTest();
481         }
482     }
483 
484     protected void runTestProfiled() throws Throwable {
485         for (int i = 0; i < 2; i++) {
486             long startTime = System.nanoTime();
487             super.runTest();
488             long elapsedMillis = millisElapsedSince(startTime);
489             if (elapsedMillis < profileThreshold)
490                 break;
491             // Never report first run of any test; treat it as a
492             // warmup run, notably to trigger all needed classloading,
493             if (i > 0)
494                 System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
495         }
496     }
497     */
498     // END Android-removed: Not used for JUnit4.
499 
500     /**
501      * Runs all JSR166 unit tests using junit.textui.TestRunner.
502      */
main(String[] args)503     public static void main(String[] args) {
504         // Android-changed: Use JUnitCore.main.
505         // main(suite(), args);
506         // org.junit.runner.JUnitCore.main("test.java.util.concurrent.tck.JSR166TestCase");
507     }
508 
509     // BEGIN Android-removed: Not needed for JUnit4.
510     /*
511     static class PithyResultPrinter extends junit.textui.ResultPrinter {
512         PithyResultPrinter(java.io.PrintStream writer) { super(writer); }
513         long runTime;
514         public void startTest(Test test) {}
515         protected void printHeader(long runTime) {
516             this.runTime = runTime; // defer printing for later
517         }
518         protected void printFooter(TestResult result) {
519             if (result.wasSuccessful()) {
520                 getWriter().println("OK (" + result.runCount() + " tests)"
521                     + "  Time: " + elapsedTimeAsString(runTime));
522             } else {
523                 getWriter().println("Time: " + elapsedTimeAsString(runTime));
524                 super.printFooter(result);
525             }
526         }
527     }
528 
529     /**
530      * Returns a TestRunner that doesn't bother with unnecessary
531      * fluff, like printing a "." for each test case.
532      * /
533     static junit.textui.TestRunner newPithyTestRunner() {
534         junit.textui.TestRunner runner = new junit.textui.TestRunner();
535         runner.setPrinter(new PithyResultPrinter(System.out));
536         return runner;
537     }
538 
539     /**
540      * Runs all unit tests in the given test suite.
541      * Actual behavior influenced by jsr166.* system properties.
542      * /
543     static void main(Test suite, String[] args) {
544         if (useSecurityManager) {
545             System.err.println("Setting a permissive security manager");
546             Policy.setPolicy(permissivePolicy());
547             System.setSecurityManager(new SecurityManager());
548         }
549         for (int i = 0; i < suiteRuns; i++) {
550             TestResult result = newPithyTestRunner().doRun(suite);
551             if (!result.wasSuccessful())
552                 System.exit(1);
553             System.gc();
554             System.runFinalization();
555         }
556     }
557 
558     public static TestSuite newTestSuite(Object... suiteOrClasses) {
559         TestSuite suite = new TestSuite();
560         for (Object suiteOrClass : suiteOrClasses) {
561             // Android-added: Ignore null and CollectionTest. http://b/285113029
562             if (suiteOrClass == null) {
563                 continue;
564             }
565 
566             if (suiteOrClass instanceof TestSuite)
567                 suite.addTest((TestSuite) suiteOrClass);
568             else if (suiteOrClass instanceof Class)
569                 suite.addTest(new TestSuite((Class<?>) suiteOrClass));
570             else
571                 throw new ClassCastException("not a test suite or class");
572         }
573         return suite;
574     }
575 
576     public static void addNamedTestClasses(TestSuite suite,
577                                            String... testClassNames) {
578         for (String testClassName : testClassNames) {
579             try {
580                 Class<?> testClass = Class.forName(testClassName);
581                 Method m = testClass.getDeclaredMethod("suite",
582                                                        new Class<?>[0]);
583                 suite.addTest(newTestSuite((Test)m.invoke(null)));
584             } catch (Exception e) {
585                 throw new Error("Missing test class", e);
586             }
587         }
588     }
589     */
590     // END Android-removed: Not needed for JUnit4.
591 
592     public static final double JAVA_CLASS_VERSION;
593     public static final String JAVA_SPECIFICATION_VERSION;
594     static {
595         try {
596             JAVA_CLASS_VERSION = java.security.AccessController.doPrivileged(
597                 new java.security.PrivilegedAction<Double>() {
598                 public Double run() {
599                     return Double.valueOf(System.getProperty("java.class.version"));}});
600             JAVA_SPECIFICATION_VERSION = java.security.AccessController.doPrivileged(
601                 new java.security.PrivilegedAction<String>() {
602                 public String run() {
603                     return System.getProperty("java.specification.version");}});
604         } catch (Throwable t) {
605             throw new Error(t);
606         }
607     }
608 
atLeastJava6()609     public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
atLeastJava7()610     public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
atLeastJava8()611     public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
atLeastJava9()612     public static boolean atLeastJava9() {
613         return JAVA_CLASS_VERSION >= 53.0
614             // As of 2015-09, java9 still uses 52.0 class file version
615             || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?(9|[0-9][0-9])$");
616     }
atLeastJava10()617     public static boolean atLeastJava10() {
618         return JAVA_CLASS_VERSION >= 54.0
619             || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?[0-9][0-9]$");
620     }
621 
622     // BEGIN Android-removed: Use JUnit4's SuiteClasses annotation.
623     /*
624     /**
625      * Collects all JSR166 unit tests as one suite.
626      * /
627     public static Test suite() {
628         // Java7+ test classes
629         TestSuite suite = newTestSuite(
630             ForkJoinPoolTest.suite(),
631             ForkJoinTaskTest.suite(),
632             RecursiveActionTest.suite(),
633             RecursiveTaskTest.suite(),
634             LinkedTransferQueueTest.suite(),
635             PhaserTest.suite(),
636             ThreadLocalRandomTest.suite(),
637             AbstractExecutorServiceTest.suite(),
638             AbstractQueueTest.suite(),
639             AbstractQueuedSynchronizerTest.suite(),
640             AbstractQueuedLongSynchronizerTest.suite(),
641             ArrayBlockingQueueTest.suite(),
642             ArrayDequeTest.suite(),
643             ArrayListTest.suite(),
644             AtomicBooleanTest.suite(),
645             AtomicIntegerArrayTest.suite(),
646             AtomicIntegerFieldUpdaterTest.suite(),
647             AtomicIntegerTest.suite(),
648             AtomicLongArrayTest.suite(),
649             AtomicLongFieldUpdaterTest.suite(),
650             AtomicLongTest.suite(),
651             AtomicMarkableReferenceTest.suite(),
652             AtomicReferenceArrayTest.suite(),
653             AtomicReferenceFieldUpdaterTest.suite(),
654             AtomicReferenceTest.suite(),
655             AtomicStampedReferenceTest.suite(),
656             ConcurrentHashMapTest.suite(),
657             ConcurrentLinkedDequeTest.suite(),
658             ConcurrentLinkedQueueTest.suite(),
659             ConcurrentSkipListMapTest.suite(),
660             ConcurrentSkipListSubMapTest.suite(),
661             ConcurrentSkipListSetTest.suite(),
662             ConcurrentSkipListSubSetTest.suite(),
663             CopyOnWriteArrayListTest.suite(),
664             CopyOnWriteArraySetTest.suite(),
665             CountDownLatchTest.suite(),
666             CountedCompleterTest.suite(),
667             CyclicBarrierTest.suite(),
668             DelayQueueTest.suite(),
669             EntryTest.suite(),
670             ExchangerTest.suite(),
671             ExecutorsTest.suite(),
672             ExecutorCompletionServiceTest.suite(),
673             FutureTaskTest.suite(),
674             LinkedBlockingDequeTest.suite(),
675             LinkedBlockingQueueTest.suite(),
676             LinkedListTest.suite(),
677             LockSupportTest.suite(),
678             PriorityBlockingQueueTest.suite(),
679             PriorityQueueTest.suite(),
680             ReentrantLockTest.suite(),
681             ReentrantReadWriteLockTest.suite(),
682             ScheduledExecutorTest.suite(),
683             ScheduledExecutorSubclassTest.suite(),
684             SemaphoreTest.suite(),
685             SynchronousQueueTest.suite(),
686             SystemTest.suite(),
687             ThreadLocalTest.suite(),
688             ThreadPoolExecutorTest.suite(),
689             ThreadPoolExecutorSubclassTest.suite(),
690             ThreadTest.suite(),
691             TimeUnitTest.suite(),
692             TreeMapTest.suite(),
693             TreeSetTest.suite(),
694             TreeSubMapTest.suite(),
695             TreeSubSetTest.suite(),
696             VectorTest.suite());
697 
698         // Java8+ test classes
699         if (atLeastJava8()) {
700             String[] java8TestClassNames = {
701                 "ArrayDeque8Test",
702                 "Atomic8Test",
703                 "CompletableFutureTest",
704                 "ConcurrentHashMap8Test",
705                 "CountedCompleter8Test",
706                 "DoubleAccumulatorTest",
707                 "DoubleAdderTest",
708                 "ForkJoinPool8Test",
709                 "ForkJoinTask8Test",
710                 "LinkedBlockingDeque8Test",
711                 "LinkedBlockingQueue8Test",
712                 "LongAccumulatorTest",
713                 "LongAdderTest",
714                 "SplittableRandomTest",
715                 "StampedLockTest",
716                 "SubmissionPublisherTest",
717                 "ThreadLocalRandom8Test",
718                 "TimeUnit8Test",
719             };
720             addNamedTestClasses(suite, java8TestClassNames);
721         }
722 
723         // Java9+ test classes
724         if (atLeastJava9()) {
725             String[] java9TestClassNames = {
726                 "AtomicBoolean9Test",
727                 "AtomicInteger9Test",
728                 "AtomicIntegerArray9Test",
729                 "AtomicLong9Test",
730                 "AtomicLongArray9Test",
731                 "AtomicReference9Test",
732                 "AtomicReferenceArray9Test",
733                 "ExecutorCompletionService9Test",
734                 "ForkJoinPool9Test",
735                 "SubmissionPublisherTest",
736             };
737             addNamedTestClasses(suite, java9TestClassNames);
738         }
739 
740         return suite;
741     }
742 
743     /** Returns list of junit-style test method names in given class. * /
744     public static ArrayList<String> testMethodNames(Class<?> testClass) {
745         Method[] methods = testClass.getDeclaredMethods();
746         ArrayList<String> names = new ArrayList<>(methods.length);
747         for (Method method : methods) {
748             if (method.getName().startsWith("test")
749                 && Modifier.isPublic(method.getModifiers())
750                 // method.getParameterCount() requires jdk8+
751                 && method.getParameterTypes().length == 0) {
752                 names.add(method.getName());
753             }
754         }
755         return names;
756     }
757 
758     /**
759      * Returns junit-style testSuite for the given test class, but
760      * parameterized by passing extra data to each test.
761      * /
762     public static <ExtraData> Test parameterizedTestSuite
763         (Class<? extends JSR166TestCase> testClass,
764          Class<ExtraData> dataClass,
765          ExtraData data) {
766         try {
767             TestSuite suite = new TestSuite();
768             Constructor c =
769                 testClass.getDeclaredConstructor(dataClass, String.class);
770             for (String methodName : testMethodNames(testClass))
771                 suite.addTest((Test) c.newInstance(data, methodName));
772             return suite;
773         } catch (Exception e) {
774             throw new Error(e);
775         }
776     }
777 
778     /**
779      * Returns junit-style testSuite for the jdk8 extension of the
780      * given test class, but parameterized by passing extra data to
781      * each test.  Uses reflection to allow compilation in jdk7.
782      * /
783     public static <ExtraData> Test jdk8ParameterizedTestSuite
784         (Class<? extends JSR166TestCase> testClass,
785          Class<ExtraData> dataClass,
786          ExtraData data) {
787         if (atLeastJava8()) {
788             String name = testClass.getName();
789             String name8 = name.replaceAll("Test$", "8Test");
790             if (name.equals(name8)) throw new Error(name);
791             try {
792                 return (Test)
793                     Class.forName(name8)
794                     .getMethod("testSuite", new Class[] { dataClass })
795                     .invoke(null, data);
796             } catch (Exception e) {
797                 throw new Error(e);
798             }
799         } else {
800             return new TestSuite();
801         }
802     }
803     */
804     // END Android-removed: Use JUnit4's SuiteClasses annotation.
805 
806     // Delays for timing-dependent tests, in milliseconds.
807 
808     public static long SHORT_DELAY_MS;
809     public static long SMALL_DELAY_MS;
810     public static long MEDIUM_DELAY_MS;
811     public static long LONG_DELAY_MS;
812 
813     /**
814      * A delay significantly longer than LONG_DELAY_MS.
815      * Use this in a thread that is waited for via awaitTermination(Thread).
816      */
817     public static long LONGER_DELAY_MS;
818 
819     private static final long RANDOM_TIMEOUT;
820     private static final long RANDOM_EXPIRED_TIMEOUT;
821     private static final TimeUnit RANDOM_TIMEUNIT;
822     static {
823         ThreadLocalRandom rnd = ThreadLocalRandom.current();
824         long[] timeouts = { Long.MIN_VALUE, -1, 0, 1, Long.MAX_VALUE };
825         RANDOM_TIMEOUT = timeouts[rnd.nextInt(timeouts.length)];
826         RANDOM_EXPIRED_TIMEOUT = timeouts[rnd.nextInt(3)];
827         TimeUnit[] timeUnits = TimeUnit.values();
828         RANDOM_TIMEUNIT = timeUnits[rnd.nextInt(timeUnits.length)];
829     }
830 
831     /**
832      * Returns a timeout for use when any value at all will do.
833      */
randomTimeout()834     static long randomTimeout() { return RANDOM_TIMEOUT; }
835 
836     /**
837      * Returns a timeout that means "no waiting", i.e. not positive.
838      */
randomExpiredTimeout()839     static long randomExpiredTimeout() { return RANDOM_EXPIRED_TIMEOUT; }
840 
841     /**
842      * Returns a random non-null TimeUnit.
843      */
randomTimeUnit()844     static TimeUnit randomTimeUnit() { return RANDOM_TIMEUNIT; }
845 
846     /**
847      * Returns the shortest timed delay. This can be scaled up for
848      * slow machines using the jsr166.delay.factor system property,
849      * or via jtreg's -timeoutFactor: flag.
850      * http://openjdk.java.net/jtreg/command-help.html
851      */
getShortDelay()852     protected long getShortDelay() {
853         return (long) (50 * delayFactor);
854     }
855 
856     /**
857      * Sets delays as multiples of SHORT_DELAY.
858      */
setDelays()859     protected void setDelays() {
860         SHORT_DELAY_MS = getShortDelay();
861         SMALL_DELAY_MS  = SHORT_DELAY_MS * 5;
862         MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
863         LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
864     }
865 
866     /**
867      * Returns a timeout in milliseconds to be used in tests that
868      * verify that operations block or time out.
869      */
timeoutMillis()870     long timeoutMillis() {
871         return SHORT_DELAY_MS / 4;
872     }
873 
874     /**
875      * Returns a new Date instance representing a time at least
876      * delayMillis milliseconds in the future.
877      */
delayedDate(long delayMillis)878     Date delayedDate(long delayMillis) {
879         // Add 1 because currentTimeMillis is known to round into the past.
880         return new Date(System.currentTimeMillis() + delayMillis + 1);
881     }
882 
883     /**
884      * The first exception encountered if any threadAssertXXX method fails.
885      */
886     private final AtomicReference<Throwable> threadFailure
887         = new AtomicReference<>(null);
888 
889     /**
890      * Records an exception so that it can be rethrown later in the test
891      * harness thread, triggering a test case failure.  Only the first
892      * failure is recorded; subsequent calls to this method from within
893      * the same test have no effect.
894      */
threadRecordFailure(Throwable t)895     public void threadRecordFailure(Throwable t) {
896         System.err.println(t);
897         dumpTestThreads();
898         threadFailure.compareAndSet(null, t);
899     }
900 
901     @Before
setUp()902     public void setUp() {
903         setDelays();
904     }
905 
tearDownFail(String format, Object... args)906     void tearDownFail(String format, Object... args) {
907         String msg = toString() + ": " + String.format(format, args);
908         System.err.println(msg);
909         dumpTestThreads();
910         fail(msg);
911     }
912 
913     /**
914      * Extra checks that get done for all test cases.
915      *
916      * Triggers test case failure if any thread assertions have failed,
917      * by rethrowing, in the test harness thread, any exception recorded
918      * earlier by threadRecordFailure.
919      *
920      * Triggers test case failure if interrupt status is set in the main thread.
921      */
922     @After
tearDown()923     public void tearDown() throws Exception {
924         Throwable t = threadFailure.getAndSet(null);
925         if (t != null) {
926             if (t instanceof Error)
927                 throw (Error) t;
928             else if (t instanceof RuntimeException)
929                 throw (RuntimeException) t;
930             else if (t instanceof Exception)
931                 throw (Exception) t;
932             else {
933                 failWithCause(t);
934             }
935         }
936 
937         if (Thread.interrupted())
938             tearDownFail("interrupt status set in main thread");
939 
940         checkForkJoinPoolThreadLeaks();
941     }
942 
943     // Android-added: Mechanism for throwing a failure with a specified cause
944     // This is needed since AssertionFailedError has been removed in JUnit 4.
failWithCause(Throwable cause, String msg)945     public static void failWithCause(Throwable cause, String msg) {
946         try {
947             fail(msg);
948         } catch (Throwable afe) {
949             afe.initCause(cause);
950             throw afe;
951         }
952     }
failWithCause(Throwable cause)953     public static void failWithCause(Throwable cause) {
954         failWithCause(cause, cause.toString());
955     }
956 
957     /**
958      * Finds missing PoolCleaners
959      */
checkForkJoinPoolThreadLeaks()960     void checkForkJoinPoolThreadLeaks() throws InterruptedException {
961         Thread[] survivors = new Thread[7];
962         int count = Thread.enumerate(survivors);
963         for (int i = 0; i < count; i++) {
964             Thread thread = survivors[i];
965             String name = thread.getName();
966             if (name.startsWith("ForkJoinPool-")) {
967                 // give thread some time to terminate
968                 thread.join(LONG_DELAY_MS);
969                 if (thread.isAlive())
970                     tearDownFail("Found leaked ForkJoinPool thread thread=%s",
971                                  thread);
972             }
973         }
974 
975         if (!ForkJoinPool.commonPool()
976             .awaitQuiescence(LONG_DELAY_MS, MILLISECONDS))
977             tearDownFail("ForkJoin common pool thread stuck");
978     }
979 
980     /**
981      * Just like fail(reason), but additionally recording (using
982      * threadRecordFailure) any AssertionError thrown, so that
983      * the current testcase will fail.
984      */
threadFail(String reason)985     public void threadFail(String reason) {
986         try {
987             fail(reason);
988         } catch (AssertionError t) {
989             threadRecordFailure(t);
990             throw t;
991         }
992     }
993 
994     /**
995      * Just like assertTrue(b), but additionally recording (using
996      * threadRecordFailure) any AssertionError thrown, so that
997      * the current testcase will fail.
998      */
threadAssertTrue(boolean b)999     public void threadAssertTrue(boolean b) {
1000         try {
1001             assertTrue(b);
1002         } catch (AssertionError t) {
1003             threadRecordFailure(t);
1004             throw t;
1005         }
1006     }
1007 
1008     /**
1009      * Just like assertFalse(b), but additionally recording (using
1010      * threadRecordFailure) any AssertionError thrown, so that
1011      * the current testcase will fail.
1012      */
threadAssertFalse(boolean b)1013     public void threadAssertFalse(boolean b) {
1014         try {
1015             assertFalse(b);
1016         } catch (AssertionError t) {
1017             threadRecordFailure(t);
1018             throw t;
1019         }
1020     }
1021 
1022     /**
1023      * Just like assertNull(x), but additionally recording (using
1024      * threadRecordFailure) any AssertionError thrown, so that
1025      * the current testcase will fail.
1026      */
threadAssertNull(Object x)1027     public void threadAssertNull(Object x) {
1028         try {
1029             assertNull(x);
1030         } catch (AssertionError t) {
1031             threadRecordFailure(t);
1032             throw t;
1033         }
1034     }
1035 
1036     /**
1037      * Just like assertEquals(x, y), but additionally recording (using
1038      * threadRecordFailure) any AssertionError thrown, so that
1039      * the current testcase will fail.
1040      */
threadAssertEquals(long x, long y)1041     public void threadAssertEquals(long x, long y) {
1042         try {
1043             assertEquals(x, y);
1044         } catch (AssertionError t) {
1045             threadRecordFailure(t);
1046             throw t;
1047         }
1048     }
1049 
1050     /**
1051      * Just like assertEquals(x, y), but additionally recording (using
1052      * threadRecordFailure) any AssertionError thrown, so that
1053      * the current testcase will fail.
1054      */
threadAssertEquals(Object x, Object y)1055     public void threadAssertEquals(Object x, Object y) {
1056         try {
1057             assertEquals(x, y);
1058         } catch (AssertionError fail) {
1059             threadRecordFailure(fail);
1060             throw fail;
1061         } catch (Throwable fail) {
1062             threadUnexpectedException(fail);
1063         }
1064     }
1065 
1066     /**
1067      * Just like assertSame(x, y), but additionally recording (using
1068      * threadRecordFailure) any AssertionError thrown, so that
1069      * the current testcase will fail.
1070      */
threadAssertSame(Object x, Object y)1071     public void threadAssertSame(Object x, Object y) {
1072         try {
1073             assertSame(x, y);
1074         } catch (AssertionError fail) {
1075             threadRecordFailure(fail);
1076             throw fail;
1077         }
1078     }
1079 
1080     /**
1081      * Calls threadFail with message "should throw exception".
1082      */
threadShouldThrow()1083     public void threadShouldThrow() {
1084         threadFail("should throw exception");
1085     }
1086 
1087     /**
1088      * Calls threadFail with message "should throw" + exceptionName.
1089      */
threadShouldThrow(String exceptionName)1090     public void threadShouldThrow(String exceptionName) {
1091         threadFail("should throw " + exceptionName);
1092     }
1093 
1094     /**
1095      * Records the given exception using {@link #threadRecordFailure},
1096      * then rethrows the exception, wrapping it in an
1097      * AssertionError if necessary.
1098      */
threadUnexpectedException(Throwable t)1099     public void threadUnexpectedException(Throwable t) {
1100         threadRecordFailure(t);
1101         t.printStackTrace();
1102         if (t instanceof RuntimeException)
1103             throw (RuntimeException) t;
1104         else if (t instanceof Error)
1105             throw (Error) t;
1106         else {
1107             failWithCause(t, "unexpected exception: " + t);
1108         }
1109     }
1110 
1111     /**
1112      * Delays, via Thread.sleep, for the given millisecond delay, but
1113      * if the sleep is shorter than specified, may re-sleep or yield
1114      * until time elapses.  Ensures that the given time, as measured
1115      * by System.nanoTime(), has elapsed.
1116      */
delay(long millis)1117     static void delay(long millis) throws InterruptedException {
1118         long nanos = millis * (1000 * 1000);
1119         final long wakeupTime = System.nanoTime() + nanos;
1120         do {
1121             if (millis > 0L)
1122                 Thread.sleep(millis);
1123             else // too short to sleep
1124                 Thread.yield();
1125             nanos = wakeupTime - System.nanoTime();
1126             millis = nanos / (1000 * 1000);
1127         } while (nanos >= 0L);
1128     }
1129 
1130     /**
1131      * Allows use of try-with-resources with per-test thread pools.
1132      */
1133     class PoolCleaner implements AutoCloseable {
1134         private final ExecutorService pool;
PoolCleaner(ExecutorService pool)1135         public PoolCleaner(ExecutorService pool) { this.pool = pool; }
close()1136         public void close() { joinPool(pool); }
1137     }
1138 
1139     /**
1140      * An extension of PoolCleaner that has an action to release the pool.
1141      */
1142     class PoolCleanerWithReleaser extends PoolCleaner {
1143         private final Runnable releaser;
PoolCleanerWithReleaser(ExecutorService pool, Runnable releaser)1144         public PoolCleanerWithReleaser(ExecutorService pool, Runnable releaser) {
1145             super(pool);
1146             this.releaser = releaser;
1147         }
close()1148         public void close() {
1149             try {
1150                 releaser.run();
1151             } finally {
1152                 super.close();
1153             }
1154         }
1155     }
1156 
cleaner(ExecutorService pool)1157     PoolCleaner cleaner(ExecutorService pool) {
1158         return new PoolCleaner(pool);
1159     }
1160 
cleaner(ExecutorService pool, Runnable releaser)1161     PoolCleaner cleaner(ExecutorService pool, Runnable releaser) {
1162         return new PoolCleanerWithReleaser(pool, releaser);
1163     }
1164 
cleaner(ExecutorService pool, CountDownLatch latch)1165     PoolCleaner cleaner(ExecutorService pool, CountDownLatch latch) {
1166         return new PoolCleanerWithReleaser(pool, releaser(latch));
1167     }
1168 
releaser(final CountDownLatch latch)1169     Runnable releaser(final CountDownLatch latch) {
1170         return new Runnable() { public void run() {
1171             do { latch.countDown(); }
1172             while (latch.getCount() > 0);
1173         }};
1174     }
1175 
1176     PoolCleaner cleaner(ExecutorService pool, AtomicBoolean flag) {
1177         return new PoolCleanerWithReleaser(pool, releaser(flag));
1178     }
1179 
1180     Runnable releaser(final AtomicBoolean flag) {
1181         return new Runnable() { public void run() { flag.set(true); }};
1182     }
1183 
1184     /**
1185      * Waits out termination of a thread pool or fails doing so.
1186      */
1187     void joinPool(ExecutorService pool) {
1188         try {
1189             pool.shutdown();
1190             if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS)) {
1191                 try {
1192                     threadFail("ExecutorService " + pool +
1193                                " did not terminate in a timely manner");
1194                 } finally {
1195                     // last resort, for the benefit of subsequent tests
1196                     pool.shutdownNow();
1197                     pool.awaitTermination(MEDIUM_DELAY_MS, MILLISECONDS);
1198                 }
1199             }
1200         } catch (SecurityException ok) {
1201             // Allowed in case test doesn't have privs
1202         } catch (InterruptedException fail) {
1203             threadFail("Unexpected InterruptedException");
1204         }
1205     }
1206 
1207     /**
1208      * Like Runnable, but with the freedom to throw anything.
1209      * junit folks had the same idea:
1210      * http://junit.org/junit5/docs/snapshot/api/org/junit/gen5/api/Executable.html
1211      */
1212     interface Action { public void run() throws Throwable; }
1213 
1214     /**
1215      * Runs all the given actions in parallel, failing if any fail.
1216      * Useful for running multiple variants of tests that are
1217      * necessarily individually slow because they must block.
1218      */
1219     protected void testInParallel(Action ... actions) {
1220         ExecutorService pool = Executors.newCachedThreadPool();
1221         try (PoolCleaner cleaner = cleaner(pool)) {
1222             ArrayList<Future<?>> futures = new ArrayList<>(actions.length);
1223             for (final Action action : actions)
1224                 futures.add(pool.submit(new CheckedRunnable() {
1225                     public void realRun() throws Throwable { action.run();}}));
1226             for (Future<?> future : futures)
1227                 try {
1228                     assertNull(future.get(LONG_DELAY_MS, MILLISECONDS));
1229                 } catch (ExecutionException ex) {
1230                     threadUnexpectedException(ex.getCause());
1231                 } catch (Exception ex) {
1232                     threadUnexpectedException(ex);
1233                 }
1234         }
1235     }
1236 
1237     /**
1238      * A debugging tool to print stack traces of most threads, as jstack does.
1239      * Uninteresting threads are filtered out.
1240      */
1241     static void dumpTestThreads() {
1242         SecurityManager sm = System.getSecurityManager();
1243         if (sm != null) {
1244             try {
1245                 System.setSecurityManager(null);
1246             } catch (SecurityException giveUp) {
1247                 return;
1248             }
1249         }
1250 
1251         // Android-removed: Android doesn't have ManagementFactory.
1252         /*
1253         ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
1254         System.err.println("------ stacktrace dump start ------");
1255         for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) {
1256             final String name = info.getThreadName();
1257             String lockName;
1258             if ("Signal Dispatcher".equals(name))
1259                 continue;
1260             if ("Reference Handler".equals(name)
1261                 && (lockName = info.getLockName()) != null
1262                 && lockName.startsWith("java.lang.ref.Reference$Lock"))
1263                 continue;
1264             if ("Finalizer".equals(name)
1265                 && (lockName = info.getLockName()) != null
1266                 && lockName.startsWith("java.lang.ref.ReferenceQueue$Lock"))
1267                 continue;
1268             if ("checkForWedgedTest".equals(name))
1269                 continue;
1270             System.err.print(info);
1271         }
1272         System.err.println("------ stacktrace dump end ------");
1273         */
1274 
1275         if (sm != null) System.setSecurityManager(sm);
1276     }
1277 
1278     /**
1279      * Checks that thread does not terminate within the default
1280      * millisecond delay of {@code timeoutMillis()}.
1281      */
1282     void assertThreadStaysAlive(Thread thread) {
1283         assertThreadStaysAlive(thread, timeoutMillis());
1284     }
1285 
1286     /**
1287      * Checks that thread does not terminate within the given millisecond delay.
1288      */
1289     void assertThreadStaysAlive(Thread thread, long millis) {
1290         try {
1291             // No need to optimize the failing case via Thread.join.
1292             delay(millis);
1293             assertTrue(thread.isAlive());
1294         } catch (InterruptedException fail) {
1295             threadFail("Unexpected InterruptedException");
1296         }
1297     }
1298 
1299     /**
1300      * Checks that the threads do not terminate within the default
1301      * millisecond delay of {@code timeoutMillis()}.
1302      */
1303     void assertThreadsStayAlive(Thread... threads) {
1304         assertThreadsStayAlive(timeoutMillis(), threads);
1305     }
1306 
1307     /**
1308      * Checks that the threads do not terminate within the given millisecond delay.
1309      */
1310     void assertThreadsStayAlive(long millis, Thread... threads) {
1311         try {
1312             // No need to optimize the failing case via Thread.join.
1313             delay(millis);
1314             for (Thread thread : threads)
1315                 assertTrue(thread.isAlive());
1316         } catch (InterruptedException fail) {
1317             threadFail("Unexpected InterruptedException");
1318         }
1319     }
1320 
1321     /**
1322      * Checks that future.get times out, with the default timeout of
1323      * {@code timeoutMillis()}.
1324      */
1325     void assertFutureTimesOut(Future future) {
1326         assertFutureTimesOut(future, timeoutMillis());
1327     }
1328 
1329     /**
1330      * Checks that future.get times out, with the given millisecond timeout.
1331      */
1332     void assertFutureTimesOut(Future future, long timeoutMillis) {
1333         long startTime = System.nanoTime();
1334         try {
1335             future.get(timeoutMillis, MILLISECONDS);
1336             shouldThrow();
1337         } catch (TimeoutException success) {
1338         } catch (Exception fail) {
1339             threadUnexpectedException(fail);
1340         } finally { future.cancel(true); }
1341         assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
1342     }
1343 
1344     /**
1345      * Fails with message "should throw exception".
1346      */
1347     public void shouldThrow() {
1348         fail("Should throw exception");
1349     }
1350 
1351     /**
1352      * Fails with message "should throw " + exceptionName.
1353      */
1354     public void shouldThrow(String exceptionName) {
1355         fail("Should throw " + exceptionName);
1356     }
1357 
1358     /**
1359      * The number of elements to place in collections, arrays, etc.
1360      */
1361     public static final int SIZE = 20;
1362 
1363     // Some convenient Integer constants
1364 
1365     public static final Integer zero  = new Integer(0);
1366     public static final Integer one   = new Integer(1);
1367     public static final Integer two   = new Integer(2);
1368     public static final Integer three = new Integer(3);
1369     public static final Integer four  = new Integer(4);
1370     public static final Integer five  = new Integer(5);
1371     public static final Integer six   = new Integer(6);
1372     public static final Integer seven = new Integer(7);
1373     public static final Integer eight = new Integer(8);
1374     public static final Integer nine  = new Integer(9);
1375     public static final Integer m1  = new Integer(-1);
1376     public static final Integer m2  = new Integer(-2);
1377     public static final Integer m3  = new Integer(-3);
1378     public static final Integer m4  = new Integer(-4);
1379     public static final Integer m5  = new Integer(-5);
1380     public static final Integer m6  = new Integer(-6);
1381     public static final Integer m10 = new Integer(-10);
1382 
1383     static Item[] seqItems(int size) {
1384         Item[] s = new Item[size];
1385         for (int i = 0; i < size; ++i)
1386             s[i] = new Item(i);
1387         return s;
1388     }
1389     static Item[] negativeSeqItems(int size) {
1390         Item[] s = new Item[size];
1391         for (int i = 0; i < size; ++i)
1392             s[i] = new Item(-i);
1393         return s;
1394     }
1395 
1396     // Many tests rely on defaultItems all being sequential nonnegative
1397     public static final Item[] defaultItems = seqItems(SIZE);
1398 
1399     static Item itemFor(int i) { // check cache for defaultItems
1400         Item[] items = defaultItems;
1401         return (i >= 0 && i < items.length) ? items[i] : new Item(i);
1402     }
1403 
1404     public static final Item itemZero  = defaultItems[0];
1405     public static final Item itemOne   = defaultItems[1];
1406     public static final Item itemTwo   = defaultItems[2];
1407     public static final Item itemThree = defaultItems[3];
1408     public static final Item itemFour  = defaultItems[4];
1409     public static final Item itemFive  = defaultItems[5];
1410     public static final Item itemSix   = defaultItems[6];
1411     public static final Item itemSeven = defaultItems[7];
1412     public static final Item itemEight = defaultItems[8];
1413     public static final Item itemNine  = defaultItems[9];
1414     public static final Item itemTen   = defaultItems[10];
1415 
1416     public static final Item[] negativeItems = negativeSeqItems(SIZE);
1417 
1418     public static final Item minusOne   = negativeItems[1];
1419     public static final Item minusTwo   = negativeItems[2];
1420     public static final Item minusThree = negativeItems[3];
1421     public static final Item minusFour  = negativeItems[4];
1422     public static final Item minusFive  = negativeItems[5];
1423     public static final Item minusSix   = negativeItems[6];
1424     public static final Item minusSeven = negativeItems[7];
1425     public static final Item minusEight = negativeItems[8];
1426     public static final Item minusNone  = negativeItems[9];
1427     public static final Item minusTen   = negativeItems[10];
1428 
1429     // elements expected to be missing
1430     public static final Item fortytwo = new Item(42);
1431     public static final Item eightysix = new Item(86);
1432     public static final Item ninetynine = new Item(99);
1433 
1434     // Interop across Item, int
1435 
1436     static void mustEqual(Item x, Item y) {
1437         if (x != y)
1438             assertEquals(x.value, y.value);
1439     }
1440     static void mustEqual(Item x, int y) {
1441         assertEquals(x.value, y);
1442     }
1443     static void mustEqual(int x, Item y) {
1444         assertEquals(x, y.value);
1445     }
1446     static void mustEqual(int x, int y) {
1447         assertEquals(x, y);
1448     }
1449     static void mustEqual(Object x, Object y) {
1450         if (x != y)
1451             assertEquals(x, y);
1452     }
1453     static void mustEqual(int x, Object y) {
1454         if (y instanceof Item)
1455             assertEquals(x, ((Item)y).value);
1456         else fail();
1457     }
1458     static void mustEqual(Object x, int y) {
1459         if (x instanceof Item)
1460             assertEquals(((Item)x).value, y);
1461         else fail();
1462     }
1463     static void mustEqual(boolean x, boolean y) {
1464         assertEquals(x, y);
1465     }
1466     static void mustEqual(long x, long y) {
1467         assertEquals(x, y);
1468     }
1469     static void mustEqual(double x, double y) {
1470         assertEquals(x, y);
1471     }
1472     static void mustContain(Collection<Item> c, int i) {
1473         assertTrue(c.contains(itemFor(i)));
1474     }
1475     static void mustContain(Collection<Item> c, Item i) {
1476         assertTrue(c.contains(i));
1477     }
1478     static void mustNotContain(Collection<Item> c, int i) {
1479         assertFalse(c.contains(itemFor(i)));
1480     }
1481     static void mustNotContain(Collection<Item> c, Item i) {
1482         assertFalse(c.contains(i));
1483     }
1484     static void mustRemove(Collection<Item> c, int i) {
1485         assertTrue(c.remove(itemFor(i)));
1486     }
1487     static void mustRemove(Collection<Item> c, Item i) {
1488         assertTrue(c.remove(i));
1489     }
1490     static void mustNotRemove(Collection<Item> c, int i) {
1491         Item[] items = defaultItems;
1492         Item x = (i >= 0 && i < items.length) ? items[i] : new Item(i);
1493         assertFalse(c.remove(x));
1494     }
1495     static void mustNotRemove(Collection<Item> c, Item i) {
1496         assertFalse(c.remove(i));
1497     }
1498     static void mustAdd(Collection<Item> c, int i) {
1499         assertTrue(c.add(itemFor(i)));
1500     }
1501     static void mustAdd(Collection<Item> c, Item i) {
1502         assertTrue(c.add(i));
1503     }
1504 
1505 
1506     /**
1507      * Runs Runnable r with a security policy that permits precisely
1508      * the specified permissions.  If there is no current security
1509      * manager, the runnable is run twice, both with and without a
1510      * security manager.  We require that any security manager permit
1511      * getPolicy/setPolicy.
1512      */
1513     public void runWithPermissions(Runnable r, Permission... permissions) {
1514         SecurityManager sm = System.getSecurityManager();
1515         if (sm == null) {
1516             r.run();
1517         }
1518         runWithSecurityManagerWithPermissions(r, permissions);
1519     }
1520 
1521     /**
1522      * Runs Runnable r with a security policy that permits precisely
1523      * the specified permissions.  If there is no current security
1524      * manager, a temporary one is set for the duration of the
1525      * Runnable.  We require that any security manager permit
1526      * getPolicy/setPolicy.
1527      */
1528     public void runWithSecurityManagerWithPermissions(Runnable r,
1529                                                       Permission... permissions) {
1530         SecurityManager sm = System.getSecurityManager();
1531         if (sm == null) {
1532             Policy savedPolicy = Policy.getPolicy();
1533             try {
1534                 Policy.setPolicy(permissivePolicy());
1535                 System.setSecurityManager(new SecurityManager());
1536                 runWithSecurityManagerWithPermissions(r, permissions);
1537             } finally {
1538                 System.setSecurityManager(null);
1539                 Policy.setPolicy(savedPolicy);
1540             }
1541         } else {
1542             Policy savedPolicy = Policy.getPolicy();
1543             AdjustablePolicy policy = new AdjustablePolicy(permissions);
1544             Policy.setPolicy(policy);
1545 
1546             try {
1547                 r.run();
1548             } finally {
1549                 policy.addPermission(new SecurityPermission("setPolicy"));
1550                 Policy.setPolicy(savedPolicy);
1551             }
1552         }
1553     }
1554 
1555     /**
1556      * Runs a runnable without any permissions.
1557      */
1558     public void runWithoutPermissions(Runnable r) {
1559         runWithPermissions(r);
1560     }
1561 
1562     /**
1563      * A security policy where new permissions can be dynamically added
1564      * or all cleared.
1565      */
1566     public static class AdjustablePolicy extends java.security.Policy {
1567         Permissions perms = new Permissions();
1568         AdjustablePolicy(Permission... permissions) {
1569             for (Permission permission : permissions)
1570                 perms.add(permission);
1571         }
1572         void addPermission(Permission perm) { perms.add(perm); }
1573         void clearPermissions() { perms = new Permissions(); }
1574         public PermissionCollection getPermissions(CodeSource cs) {
1575             return perms;
1576         }
1577         public PermissionCollection getPermissions(ProtectionDomain pd) {
1578             return perms;
1579         }
1580         public boolean implies(ProtectionDomain pd, Permission p) {
1581             return perms.implies(p);
1582         }
1583         public void refresh() {}
1584         public String toString() {
1585             List<Permission> ps = new ArrayList<>();
1586             for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
1587                 ps.add(e.nextElement());
1588             return "AdjustablePolicy with permissions " + ps;
1589         }
1590     }
1591 
1592     /**
1593      * Returns a policy containing all the permissions we ever need.
1594      */
1595     public static Policy permissivePolicy() {
1596         return new AdjustablePolicy
1597             // Permissions j.u.c. needs directly
1598             (new RuntimePermission("modifyThread"),
1599              new RuntimePermission("getClassLoader"),
1600              new RuntimePermission("setContextClassLoader"),
1601              // Permissions needed to change permissions!
1602              new SecurityPermission("getPolicy"),
1603              new SecurityPermission("setPolicy"),
1604              new RuntimePermission("setSecurityManager"),
1605              // Permissions needed by the junit test harness
1606              new RuntimePermission("accessDeclaredMembers"),
1607              new PropertyPermission("*", "read"),
1608              new java.io.FilePermission("<<ALL FILES>>", "read"));
1609     }
1610 
1611     /**
1612      * Sleeps until the given time has elapsed.
1613      * Throws AssertionError if interrupted.
1614      */
1615     static void sleep(long millis) {
1616         try {
1617             delay(millis);
1618         } catch (InterruptedException fail) {
1619             failWithCause(fail, "Unexpected InterruptedException");
1620         }
1621     }
1622 
1623     /**
1624      * Spin-waits up to the specified number of milliseconds for the given
1625      * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1626      */
1627     void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
1628         long startTime = 0L;
1629         for (;;) {
1630             Thread.State s = thread.getState();
1631             if (s == Thread.State.BLOCKED ||
1632                 s == Thread.State.WAITING ||
1633                 s == Thread.State.TIMED_WAITING)
1634                 return;
1635             else if (s == Thread.State.TERMINATED)
1636                 fail("Unexpected thread termination");
1637             else if (startTime == 0L)
1638                 startTime = System.nanoTime();
1639             else if (millisElapsedSince(startTime) > timeoutMillis) {
1640                 threadAssertTrue(thread.isAlive());
1641                 fail("timed out waiting for thread to enter wait state");
1642             }
1643             Thread.yield();
1644         }
1645     }
1646 
1647     /**
1648      * Spin-waits up to the specified number of milliseconds for the given
1649      * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING,
1650      * and additionally satisfy the given condition.
1651      */
1652     void waitForThreadToEnterWaitState(
1653         Thread thread, long timeoutMillis, Callable<Boolean> waitingForGodot) {
1654         long startTime = 0L;
1655         for (;;) {
1656             Thread.State s = thread.getState();
1657             if (s == Thread.State.BLOCKED ||
1658                 s == Thread.State.WAITING ||
1659                 s == Thread.State.TIMED_WAITING) {
1660                 try {
1661                     if (waitingForGodot.call())
1662                         return;
1663                 } catch (Throwable fail) { threadUnexpectedException(fail); }
1664             }
1665             else if (s == Thread.State.TERMINATED)
1666                 fail("Unexpected thread termination");
1667             else if (startTime == 0L)
1668                 startTime = System.nanoTime();
1669             else if (millisElapsedSince(startTime) > timeoutMillis) {
1670                 threadAssertTrue(thread.isAlive());
1671                 fail("timed out waiting for thread to enter wait state");
1672             }
1673             Thread.yield();
1674         }
1675     }
1676 
1677     /**
1678      * Spin-waits up to LONG_DELAY_MS milliseconds for the given thread to
1679      * enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1680      */
1681     void waitForThreadToEnterWaitState(Thread thread) {
1682         waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
1683     }
1684 
1685     /**
1686      * Spin-waits up to LONG_DELAY_MS milliseconds for the given thread to
1687      * enter a wait state: BLOCKED, WAITING, or TIMED_WAITING,
1688      * and additionally satisfy the given condition.
1689      */
1690     void waitForThreadToEnterWaitState(
1691         Thread thread, Callable<Boolean> waitingForGodot) {
1692         waitForThreadToEnterWaitState(thread, LONG_DELAY_MS, waitingForGodot);
1693     }
1694 
1695     /**
1696      * Returns the number of milliseconds since time given by
1697      * startNanoTime, which must have been previously returned from a
1698      * call to {@link System#nanoTime()}.
1699      */
1700     static long millisElapsedSince(long startNanoTime) {
1701         return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
1702     }
1703 
1704 //     void assertTerminatesPromptly(long timeoutMillis, Runnable r) {
1705 //         long startTime = System.nanoTime();
1706 //         try {
1707 //             r.run();
1708 //         } catch (Throwable fail) { threadUnexpectedException(fail); }
1709 //         if (millisElapsedSince(startTime) > timeoutMillis/2)
1710 //             throw new AssertionFailedError("did not return promptly");
1711 //     }
1712 
1713 //     void assertTerminatesPromptly(Runnable r) {
1714 //         assertTerminatesPromptly(LONG_DELAY_MS/2, r);
1715 //     }
1716 
1717     /**
1718      * Checks that timed f.get() returns the expected value, and does not
1719      * wait for the timeout to elapse before returning.
1720      */
1721     <T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) {
1722         long startTime = System.nanoTime();
1723         try {
1724             assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
1725         } catch (Throwable fail) { threadUnexpectedException(fail); }
1726         if (millisElapsedSince(startTime) > timeoutMillis/2)
1727             fail("timed get did not return promptly");
1728     }
1729 
1730     <T> void checkTimedGet(Future<T> f, T expectedValue) {
1731         checkTimedGet(f, expectedValue, LONG_DELAY_MS);
1732     }
1733 
1734     /**
1735      * Returns a new started daemon Thread running the given runnable.
1736      */
1737     Thread newStartedThread(Runnable runnable) {
1738         Thread t = new Thread(runnable);
1739         t.setDaemon(true);
1740         t.start();
1741         return t;
1742     }
1743 
1744     /**
1745      * Waits for the specified time (in milliseconds) for the thread
1746      * to terminate (using {@link Thread#join(long)}), else interrupts
1747      * the thread (in the hope that it may terminate later) and fails.
1748      */
1749     void awaitTermination(Thread t, long timeoutMillis) {
1750         try {
1751             t.join(timeoutMillis);
1752         } catch (InterruptedException fail) {
1753             threadUnexpectedException(fail);
1754         } finally {
1755             if (t.getState() != Thread.State.TERMINATED) {
1756                 t.interrupt();
1757                 threadFail("timed out waiting for thread to terminate");
1758             }
1759         }
1760     }
1761 
1762     /**
1763      * Waits for LONG_DELAY_MS milliseconds for the thread to
1764      * terminate (using {@link Thread#join(long)}), else interrupts
1765      * the thread (in the hope that it may terminate later) and fails.
1766      */
1767     void awaitTermination(Thread t) {
1768         awaitTermination(t, LONG_DELAY_MS);
1769     }
1770 
1771     // Some convenient Runnable classes
1772 
1773     public abstract class CheckedRunnable implements Runnable {
1774         protected abstract void realRun() throws Throwable;
1775 
1776         public final void run() {
1777             try {
1778                 realRun();
1779             } catch (Throwable fail) {
1780                 threadUnexpectedException(fail);
1781             }
1782         }
1783     }
1784 
1785     public abstract class RunnableShouldThrow implements Runnable {
1786         protected abstract void realRun() throws Throwable;
1787 
1788         final Class<?> exceptionClass;
1789 
1790         <T extends Throwable> RunnableShouldThrow(Class<T> exceptionClass) {
1791             this.exceptionClass = exceptionClass;
1792         }
1793 
1794         public final void run() {
1795             try {
1796                 realRun();
1797                 threadShouldThrow(exceptionClass.getSimpleName());
1798             } catch (Throwable t) {
1799                 if (! exceptionClass.isInstance(t))
1800                     threadUnexpectedException(t);
1801             }
1802         }
1803     }
1804 
1805     public abstract class ThreadShouldThrow extends Thread {
1806         protected abstract void realRun() throws Throwable;
1807 
1808         final Class<?> exceptionClass;
1809 
1810         <T extends Throwable> ThreadShouldThrow(Class<T> exceptionClass) {
1811             this.exceptionClass = exceptionClass;
1812         }
1813 
1814         public final void run() {
1815             try {
1816                 realRun();
1817                 threadShouldThrow(exceptionClass.getSimpleName());
1818             } catch (Throwable t) {
1819                 if (! exceptionClass.isInstance(t))
1820                     threadUnexpectedException(t);
1821             }
1822         }
1823     }
1824 
1825     public abstract class CheckedInterruptedRunnable implements Runnable {
1826         protected abstract void realRun() throws Throwable;
1827 
1828         public final void run() {
1829             try {
1830                 realRun();
1831                 threadShouldThrow("InterruptedException");
1832             } catch (InterruptedException success) {
1833                 threadAssertFalse(Thread.interrupted());
1834             } catch (Throwable fail) {
1835                 threadUnexpectedException(fail);
1836             }
1837         }
1838     }
1839 
1840     public abstract class CheckedCallable<T> implements Callable<T> {
1841         protected abstract T realCall() throws Throwable;
1842 
1843         public final T call() {
1844             try {
1845                 return realCall();
1846             } catch (Throwable fail) {
1847                 threadUnexpectedException(fail);
1848                 return null;
1849             }
1850         }
1851     }
1852 
1853     public abstract class CheckedInterruptedCallable<T>
1854         implements Callable<T> {
1855         protected abstract T realCall() throws Throwable;
1856 
1857         public final T call() {
1858             try {
1859                 T result = realCall();
1860                 threadShouldThrow("InterruptedException");
1861                 return result;
1862             } catch (InterruptedException success) {
1863                 threadAssertFalse(Thread.interrupted());
1864             } catch (Throwable fail) {
1865                 threadUnexpectedException(fail);
1866             }
1867             return null;
1868         }
1869     }
1870 
1871     public static class NoOpRunnable implements Runnable {
1872         public void run() {}
1873     }
1874 
1875     public static class NoOpCallable implements Callable {
1876         public Object call() { return Boolean.TRUE; }
1877     }
1878 
1879     public static final String TEST_STRING = "a test string";
1880 
1881     public static class StringTask implements Callable<String> {
1882         final String value;
1883         public StringTask() { this(TEST_STRING); }
1884         public StringTask(String value) { this.value = value; }
1885         public String call() { return value; }
1886     }
1887 
1888     public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
1889         return new CheckedCallable<String>() {
1890             protected String realCall() {
1891                 try {
1892                     latch.await();
1893                 } catch (InterruptedException quittingTime) {}
1894                 return TEST_STRING;
1895             }};
1896     }
1897 
1898     public Runnable countDowner(final CountDownLatch latch) {
1899         return new CheckedRunnable() {
1900             public void realRun() throws InterruptedException {
1901                 latch.countDown();
1902             }};
1903     }
1904 
1905     class LatchAwaiter extends CheckedRunnable {
1906         static final int NEW = 0;
1907         static final int RUNNING = 1;
1908         static final int DONE = 2;
1909         final CountDownLatch latch;
1910         int state = NEW;
1911         LatchAwaiter(CountDownLatch latch) { this.latch = latch; }
1912         public void realRun() throws InterruptedException {
1913             state = 1;
1914             await(latch);
1915             state = 2;
1916         }
1917     }
1918 
1919     public LatchAwaiter awaiter(CountDownLatch latch) {
1920         return new LatchAwaiter(latch);
1921     }
1922 
1923     public void await(CountDownLatch latch, long timeoutMillis) {
1924         try {
1925             if (!latch.await(timeoutMillis, MILLISECONDS))
1926                 fail("timed out waiting for CountDownLatch for "
1927                      + (timeoutMillis/1000) + " sec");
1928         } catch (Throwable fail) {
1929             threadUnexpectedException(fail);
1930         }
1931     }
1932 
1933     public void await(CountDownLatch latch) {
1934         await(latch, LONG_DELAY_MS);
1935     }
1936 
1937     public void await(Semaphore semaphore) {
1938         try {
1939             if (!semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS))
1940                 fail("timed out waiting for Semaphore for "
1941                      + (LONG_DELAY_MS/1000) + " sec");
1942         } catch (Throwable fail) {
1943             threadUnexpectedException(fail);
1944         }
1945     }
1946 
1947 //     /**
1948 //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1949 //      */
1950 //     public void await(AtomicBoolean flag) {
1951 //         await(flag, LONG_DELAY_MS);
1952 //     }
1953 
1954 //     /**
1955 //      * Spin-waits up to the specified timeout until flag becomes true.
1956 //      */
1957 //     public void await(AtomicBoolean flag, long timeoutMillis) {
1958 //         long startTime = System.nanoTime();
1959 //         while (!flag.get()) {
1960 //             if (millisElapsedSince(startTime) > timeoutMillis)
1961 //                 throw new AssertionFailedError("timed out");
1962 //             Thread.yield();
1963 //         }
1964 //     }
1965 
1966     public static class NPETask implements Callable<String> {
1967         public String call() { throw new NullPointerException(); }
1968     }
1969 
1970     public static class CallableOne implements Callable<Integer> {
1971         public Integer call() { return one; }
1972     }
1973 
1974     public class ShortRunnable extends CheckedRunnable {
1975         protected void realRun() throws Throwable {
1976             delay(SHORT_DELAY_MS);
1977         }
1978     }
1979 
1980     public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1981         protected void realRun() throws InterruptedException {
1982             delay(SHORT_DELAY_MS);
1983         }
1984     }
1985 
1986     public class SmallRunnable extends CheckedRunnable {
1987         protected void realRun() throws Throwable {
1988             delay(SMALL_DELAY_MS);
1989         }
1990     }
1991 
1992     public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1993         protected void realRun() {
1994             try {
1995                 delay(SMALL_DELAY_MS);
1996             } catch (InterruptedException ok) {}
1997         }
1998     }
1999 
2000     public class SmallCallable extends CheckedCallable {
2001         protected Object realCall() throws InterruptedException {
2002             delay(SMALL_DELAY_MS);
2003             return Boolean.TRUE;
2004         }
2005     }
2006 
2007     public class MediumRunnable extends CheckedRunnable {
2008         protected void realRun() throws Throwable {
2009             delay(MEDIUM_DELAY_MS);
2010         }
2011     }
2012 
2013     public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
2014         protected void realRun() throws InterruptedException {
2015             delay(MEDIUM_DELAY_MS);
2016         }
2017     }
2018 
2019     public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
2020         return new CheckedRunnable() {
2021             protected void realRun() {
2022                 try {
2023                     delay(timeoutMillis);
2024                 } catch (InterruptedException ok) {}
2025             }};
2026     }
2027 
2028     public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
2029         protected void realRun() {
2030             try {
2031                 delay(MEDIUM_DELAY_MS);
2032             } catch (InterruptedException ok) {}
2033         }
2034     }
2035 
2036     public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
2037         protected void realRun() {
2038             try {
2039                 delay(LONG_DELAY_MS);
2040             } catch (InterruptedException ok) {}
2041         }
2042     }
2043 
2044     /**
2045      * For use as ThreadFactory in constructors
2046      */
2047     public static class SimpleThreadFactory implements ThreadFactory {
2048         public Thread newThread(Runnable r) {
2049             return new Thread(r);
2050         }
2051     }
2052 
2053     public interface TrackedRunnable extends Runnable {
2054         boolean isDone();
2055     }
2056 
2057     public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
2058         return new TrackedRunnable() {
2059                 private volatile boolean done = false;
2060                 public boolean isDone() { return done; }
2061                 public void run() {
2062                     try {
2063                         delay(timeoutMillis);
2064                         done = true;
2065                     } catch (InterruptedException ok) {}
2066                 }
2067             };
2068     }
2069 
2070     public static class TrackedShortRunnable implements Runnable {
2071         public volatile boolean done = false;
2072         public void run() {
2073             try {
2074                 delay(SHORT_DELAY_MS);
2075                 done = true;
2076             } catch (InterruptedException ok) {}
2077         }
2078     }
2079 
2080     public static class TrackedSmallRunnable implements Runnable {
2081         public volatile boolean done = false;
2082         public void run() {
2083             try {
2084                 delay(SMALL_DELAY_MS);
2085                 done = true;
2086             } catch (InterruptedException ok) {}
2087         }
2088     }
2089 
2090     public static class TrackedMediumRunnable implements Runnable {
2091         public volatile boolean done = false;
2092         public void run() {
2093             try {
2094                 delay(MEDIUM_DELAY_MS);
2095                 done = true;
2096             } catch (InterruptedException ok) {}
2097         }
2098     }
2099 
2100     public static class TrackedLongRunnable implements Runnable {
2101         public volatile boolean done = false;
2102         public void run() {
2103             try {
2104                 delay(LONG_DELAY_MS);
2105                 done = true;
2106             } catch (InterruptedException ok) {}
2107         }
2108     }
2109 
2110     public static class TrackedNoOpRunnable implements Runnable {
2111         public volatile boolean done = false;
2112         public void run() {
2113             done = true;
2114         }
2115     }
2116 
2117     public static class TrackedCallable implements Callable {
2118         public volatile boolean done = false;
2119         public Object call() {
2120             try {
2121                 delay(SMALL_DELAY_MS);
2122                 done = true;
2123             } catch (InterruptedException ok) {}
2124             return Boolean.TRUE;
2125         }
2126     }
2127 
2128     /**
2129      * Analog of CheckedRunnable for RecursiveAction
2130      */
2131     public abstract class CheckedRecursiveAction extends RecursiveAction {
2132         protected abstract void realCompute() throws Throwable;
2133 
2134         @Override protected final void compute() {
2135             try {
2136                 realCompute();
2137             } catch (Throwable fail) {
2138                 threadUnexpectedException(fail);
2139             }
2140         }
2141     }
2142 
2143     /**
2144      * Analog of CheckedCallable for RecursiveTask
2145      */
2146     public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
2147         protected abstract T realCompute() throws Throwable;
2148 
2149         @Override protected final T compute() {
2150             try {
2151                 return realCompute();
2152             } catch (Throwable fail) {
2153                 threadUnexpectedException(fail);
2154                 return null;
2155             }
2156         }
2157     }
2158 
2159     /**
2160      * For use as RejectedExecutionHandler in constructors
2161      */
2162     public static class NoOpREHandler implements RejectedExecutionHandler {
2163         public void rejectedExecution(Runnable r,
2164                                       ThreadPoolExecutor executor) {}
2165     }
2166 
2167     /**
2168      * A CyclicBarrier that uses timed await and fails with
2169      * AssertionFailedErrors instead of throwing checked exceptions.
2170      */
2171     public static class CheckedBarrier extends CyclicBarrier {
2172         public CheckedBarrier(int parties) { super(parties); }
2173 
2174         public int await() {
2175             try {
2176                 return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
2177             } catch (TimeoutException timedOut) {
2178                 fail("timed out");
2179             } catch (Exception fail) {
2180                 failWithCause(fail, "Unexpected exception: " + fail);
2181             }
2182             return -1;
2183         }
2184     }
2185 
2186     void checkEmpty(BlockingQueue q) {
2187         try {
2188             assertTrue(q.isEmpty());
2189             assertEquals(0, q.size());
2190             assertNull(q.peek());
2191             assertNull(q.poll());
2192             assertNull(q.poll(0, MILLISECONDS));
2193             assertEquals(q.toString(), "[]");
2194             assertTrue(Arrays.equals(q.toArray(), new Object[0]));
2195             assertFalse(q.iterator().hasNext());
2196             try {
2197                 q.element();
2198                 shouldThrow();
2199             } catch (NoSuchElementException success) {}
2200             try {
2201                 q.iterator().next();
2202                 shouldThrow();
2203             } catch (NoSuchElementException success) {}
2204             try {
2205                 q.remove();
2206                 shouldThrow();
2207             } catch (NoSuchElementException success) {}
2208         } catch (InterruptedException fail) { threadUnexpectedException(fail); }
2209     }
2210 
2211     void assertSerialEquals(Object x, Object y) {
2212         assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
2213     }
2214 
2215     void assertNotSerialEquals(Object x, Object y) {
2216         assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
2217     }
2218 
2219     byte[] serialBytes(Object o) {
2220         try {
2221             ByteArrayOutputStream bos = new ByteArrayOutputStream();
2222             ObjectOutputStream oos = new ObjectOutputStream(bos);
2223             oos.writeObject(o);
2224             oos.flush();
2225             oos.close();
2226             return bos.toByteArray();
2227         } catch (Throwable fail) {
2228             threadUnexpectedException(fail);
2229             return new byte[0];
2230         }
2231     }
2232 
2233     void assertImmutable(final Object o) {
2234         if (o instanceof Collection) {
2235             assertThrows(
2236                 UnsupportedOperationException.class,
2237                 new Runnable() { public void run() {
2238                         ((Collection) o).add(null);}});
2239         }
2240     }
2241 
2242     @SuppressWarnings("unchecked")
2243     <T> T serialClone(T o) {
2244         try {
2245             ObjectInputStream ois = new ObjectInputStream
2246                 (new ByteArrayInputStream(serialBytes(o)));
2247             T clone = (T) ois.readObject();
2248             if (o == clone) assertImmutable(o);
2249             assertSame(o.getClass(), clone.getClass());
2250             return clone;
2251         } catch (Throwable fail) {
2252             threadUnexpectedException(fail);
2253             return null;
2254         }
2255     }
2256 
2257     /**
2258      * A version of serialClone that leaves error handling (for
2259      * e.g. NotSerializableException) up to the caller.
2260      */
2261     @SuppressWarnings("unchecked")
2262     <T> T serialClonePossiblyFailing(T o)
2263         throws ReflectiveOperationException, java.io.IOException {
2264         ByteArrayOutputStream bos = new ByteArrayOutputStream();
2265         ObjectOutputStream oos = new ObjectOutputStream(bos);
2266         oos.writeObject(o);
2267         oos.flush();
2268         oos.close();
2269         ObjectInputStream ois = new ObjectInputStream
2270             (new ByteArrayInputStream(bos.toByteArray()));
2271         T clone = (T) ois.readObject();
2272         if (o == clone) assertImmutable(o);
2273         assertSame(o.getClass(), clone.getClass());
2274         return clone;
2275     }
2276 
2277     /**
2278      * If o implements Cloneable and has a public clone method,
2279      * returns a clone of o, else null.
2280      */
2281     @SuppressWarnings("unchecked")
2282     <T> T cloneableClone(T o) {
2283         if (!(o instanceof Cloneable)) return null;
2284         final T clone;
2285         try {
2286             clone = (T) o.getClass().getMethod("clone").invoke(o);
2287         } catch (NoSuchMethodException ok) {
2288             return null;
2289         } catch (ReflectiveOperationException unexpected) {
2290             throw new Error(unexpected);
2291         }
2292         assertNotSame(o, clone); // not 100% guaranteed by spec
2293         assertSame(o.getClass(), clone.getClass());
2294         return clone;
2295     }
2296 
2297     public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
2298                              Runnable... throwingActions) {
2299         for (Runnable throwingAction : throwingActions) {
2300             boolean threw = false;
2301             try { throwingAction.run(); }
2302             catch (Throwable t) {
2303                 threw = true;
2304                 if (!expectedExceptionClass.isInstance(t)) {
2305                     failWithCause(t, "Expected " + expectedExceptionClass.getName() +
2306                             ", got " + t.getClass().getName());
2307                 }
2308             }
2309             if (!threw)
2310                 shouldThrow(expectedExceptionClass.getName());
2311         }
2312     }
2313 
2314     public void assertIteratorExhausted(Iterator<?> it) {
2315         try {
2316             it.next();
2317             shouldThrow();
2318         } catch (NoSuchElementException success) {}
2319         assertFalse(it.hasNext());
2320     }
2321 
2322     public <T> Callable<T> callableThrowing(final Exception ex) {
2323         return new Callable<T>() { public T call() throws Exception { throw ex; }};
2324     }
2325 
2326     public Runnable runnableThrowing(final RuntimeException ex) {
2327         return new Runnable() { public void run() { throw ex; }};
2328     }
2329 
2330     /** A reusable thread pool to be shared by tests. */
2331     static final ExecutorService cachedThreadPool =
2332         new ThreadPoolExecutor(0, Integer.MAX_VALUE,
2333                                1000L, MILLISECONDS,
2334                                new SynchronousQueue<Runnable>());
2335 
2336     static <T> void shuffle(T[] array) {
2337         Collections.shuffle(Arrays.asList(array), ThreadLocalRandom.current());
2338     }
2339 
2340     /**
2341      * Returns the same String as would be returned by {@link
2342      * Object#toString}, whether or not the given object's class
2343      * overrides toString().
2344      *
2345      * @see System#identityHashCode
2346      */
2347     static String identityString(Object x) {
2348         return x.getClass().getName()
2349             + "@" + Integer.toHexString(System.identityHashCode(x));
2350     }
2351 
2352 }
2353