ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.245
Committed: Sun Jul 22 21:19:14 2018 UTC (5 years, 9 months ago) by jsr166
Branch: MAIN
Changes since 1.244: +3 -1 lines
Log Message:
Fix errorprone warning [AssertionFailureIgnored]

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