ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.235
Committed: Sat Jul 22 18:23:59 2017 UTC (6 years, 9 months ago) by jsr166
Branch: MAIN
Changes since 1.234: +0 -47 lines
Log Message:
delete superseded assertThreadStaysAlive methods

File Contents

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