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