ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.218
Committed: Sun Jan 29 20:19:00 2017 UTC (7 years, 3 months ago) by jsr166
Branch: MAIN
Changes since 1.217: +2 -0 lines
Log Message:
add testCommonPoolThreadContextClassLoader

File Contents

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