ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.243
Committed: Thu Apr 5 03:36:54 2018 UTC (6 years, 1 month ago) by jsr166
Branch: MAIN
Changes since 1.242: +41 -0 lines
Log Message:
better testing of collection copies

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.97
455 dl 1.6 /**
456 jsr166 1.60 * Collects all JSR166 unit tests as one suite.
457 jsr166 1.27 */
458 jsr166 1.41 public static Test suite() {
459 jsr166 1.98 // Java7+ test classes
460 jsr166 1.97 TestSuite suite = newTestSuite(
461 jsr166 1.60 ForkJoinPoolTest.suite(),
462     ForkJoinTaskTest.suite(),
463     RecursiveActionTest.suite(),
464     RecursiveTaskTest.suite(),
465     LinkedTransferQueueTest.suite(),
466     PhaserTest.suite(),
467     ThreadLocalRandomTest.suite(),
468     AbstractExecutorServiceTest.suite(),
469     AbstractQueueTest.suite(),
470     AbstractQueuedSynchronizerTest.suite(),
471     AbstractQueuedLongSynchronizerTest.suite(),
472     ArrayBlockingQueueTest.suite(),
473     ArrayDequeTest.suite(),
474 jsr166 1.205 ArrayListTest.suite(),
475 jsr166 1.60 AtomicBooleanTest.suite(),
476     AtomicIntegerArrayTest.suite(),
477     AtomicIntegerFieldUpdaterTest.suite(),
478     AtomicIntegerTest.suite(),
479     AtomicLongArrayTest.suite(),
480     AtomicLongFieldUpdaterTest.suite(),
481     AtomicLongTest.suite(),
482     AtomicMarkableReferenceTest.suite(),
483     AtomicReferenceArrayTest.suite(),
484     AtomicReferenceFieldUpdaterTest.suite(),
485     AtomicReferenceTest.suite(),
486     AtomicStampedReferenceTest.suite(),
487     ConcurrentHashMapTest.suite(),
488     ConcurrentLinkedDequeTest.suite(),
489     ConcurrentLinkedQueueTest.suite(),
490     ConcurrentSkipListMapTest.suite(),
491     ConcurrentSkipListSubMapTest.suite(),
492     ConcurrentSkipListSetTest.suite(),
493     ConcurrentSkipListSubSetTest.suite(),
494     CopyOnWriteArrayListTest.suite(),
495     CopyOnWriteArraySetTest.suite(),
496     CountDownLatchTest.suite(),
497 jsr166 1.204 CountedCompleterTest.suite(),
498 jsr166 1.60 CyclicBarrierTest.suite(),
499     DelayQueueTest.suite(),
500     EntryTest.suite(),
501     ExchangerTest.suite(),
502     ExecutorsTest.suite(),
503     ExecutorCompletionServiceTest.suite(),
504     FutureTaskTest.suite(),
505     LinkedBlockingDequeTest.suite(),
506     LinkedBlockingQueueTest.suite(),
507     LinkedListTest.suite(),
508     LockSupportTest.suite(),
509     PriorityBlockingQueueTest.suite(),
510     PriorityQueueTest.suite(),
511     ReentrantLockTest.suite(),
512     ReentrantReadWriteLockTest.suite(),
513     ScheduledExecutorTest.suite(),
514     ScheduledExecutorSubclassTest.suite(),
515     SemaphoreTest.suite(),
516     SynchronousQueueTest.suite(),
517     SystemTest.suite(),
518     ThreadLocalTest.suite(),
519     ThreadPoolExecutorTest.suite(),
520     ThreadPoolExecutorSubclassTest.suite(),
521     ThreadTest.suite(),
522     TimeUnitTest.suite(),
523     TreeMapTest.suite(),
524     TreeSetTest.suite(),
525     TreeSubMapTest.suite(),
526 jsr166 1.207 TreeSubSetTest.suite(),
527     VectorTest.suite());
528 jsr166 1.98
529     // Java8+ test classes
530     if (atLeastJava8()) {
531     String[] java8TestClassNames = {
532 jsr166 1.206 "ArrayDeque8Test",
533 dl 1.113 "Atomic8Test",
534 dl 1.104 "CompletableFutureTest",
535 dl 1.105 "ConcurrentHashMap8Test",
536 jsr166 1.204 "CountedCompleter8Test",
537 dl 1.104 "DoubleAccumulatorTest",
538 dl 1.103 "DoubleAdderTest",
539 jsr166 1.102 "ForkJoinPool8Test",
540 dl 1.111 "ForkJoinTask8Test",
541 jsr166 1.237 "HashMapTest",
542 jsr166 1.215 "LinkedBlockingDeque8Test",
543     "LinkedBlockingQueue8Test",
544 dl 1.104 "LongAccumulatorTest",
545     "LongAdderTest",
546 jsr166 1.110 "SplittableRandomTest",
547 jsr166 1.98 "StampedLockTest",
548 dl 1.140 "SubmissionPublisherTest",
549 jsr166 1.112 "ThreadLocalRandom8Test",
550 jsr166 1.190 "TimeUnit8Test",
551 jsr166 1.98 };
552     addNamedTestClasses(suite, java8TestClassNames);
553 jsr166 1.97 }
554 jsr166 1.98
555 jsr166 1.115 // Java9+ test classes
556     if (atLeastJava9()) {
557     String[] java9TestClassNames = {
558 jsr166 1.196 "AtomicBoolean9Test",
559     "AtomicInteger9Test",
560     "AtomicIntegerArray9Test",
561     "AtomicLong9Test",
562     "AtomicLongArray9Test",
563     "AtomicReference9Test",
564     "AtomicReferenceArray9Test",
565 jsr166 1.192 "ExecutorCompletionService9Test",
566 jsr166 1.218 "ForkJoinPool9Test",
567 jsr166 1.115 };
568     addNamedTestClasses(suite, java9TestClassNames);
569     }
570    
571 jsr166 1.97 return suite;
572 dl 1.6 }
573    
574 jsr166 1.134 /** Returns list of junit-style test method names in given class. */
575     public static ArrayList<String> testMethodNames(Class<?> testClass) {
576     Method[] methods = testClass.getDeclaredMethods();
577 jsr166 1.216 ArrayList<String> names = new ArrayList<>(methods.length);
578 jsr166 1.134 for (Method method : methods) {
579     if (method.getName().startsWith("test")
580     && Modifier.isPublic(method.getModifiers())
581     // method.getParameterCount() requires jdk8+
582     && method.getParameterTypes().length == 0) {
583     names.add(method.getName());
584     }
585     }
586     return names;
587     }
588    
589     /**
590     * Returns junit-style testSuite for the given test class, but
591     * parameterized by passing extra data to each test.
592     */
593     public static <ExtraData> Test parameterizedTestSuite
594     (Class<? extends JSR166TestCase> testClass,
595     Class<ExtraData> dataClass,
596     ExtraData data) {
597     try {
598     TestSuite suite = new TestSuite();
599     Constructor c =
600     testClass.getDeclaredConstructor(dataClass, String.class);
601     for (String methodName : testMethodNames(testClass))
602     suite.addTest((Test) c.newInstance(data, methodName));
603     return suite;
604 jsr166 1.241 } catch (ReflectiveOperationException e) {
605     throw new AssertionError(e);
606 jsr166 1.134 }
607     }
608    
609     /**
610     * Returns junit-style testSuite for the jdk8 extension of the
611     * given test class, but parameterized by passing extra data to
612     * each test. Uses reflection to allow compilation in jdk7.
613     */
614     public static <ExtraData> Test jdk8ParameterizedTestSuite
615     (Class<? extends JSR166TestCase> testClass,
616     Class<ExtraData> dataClass,
617     ExtraData data) {
618     if (atLeastJava8()) {
619     String name = testClass.getName();
620     String name8 = name.replaceAll("Test$", "8Test");
621 jsr166 1.241 if (name.equals(name8)) throw new AssertionError(name);
622 jsr166 1.134 try {
623     return (Test)
624     Class.forName(name8)
625 jsr166 1.241 .getMethod("testSuite", dataClass)
626 jsr166 1.134 .invoke(null, data);
627 jsr166 1.241 } catch (ReflectiveOperationException e) {
628     throw new AssertionError(e);
629 jsr166 1.134 }
630     } else {
631     return new TestSuite();
632     }
633     }
634    
635 jsr166 1.109 // Delays for timing-dependent tests, in milliseconds.
636 dl 1.1
637 dl 1.2 public static long SHORT_DELAY_MS;
638     public static long SMALL_DELAY_MS;
639     public static long MEDIUM_DELAY_MS;
640     public static long LONG_DELAY_MS;
641    
642 jsr166 1.232 private static final long RANDOM_TIMEOUT;
643     private static final long RANDOM_EXPIRED_TIMEOUT;
644     private static final TimeUnit RANDOM_TIMEUNIT;
645     static {
646     ThreadLocalRandom rnd = ThreadLocalRandom.current();
647     long[] timeouts = { Long.MIN_VALUE, -1, 0, 1, Long.MAX_VALUE };
648     RANDOM_TIMEOUT = timeouts[rnd.nextInt(timeouts.length)];
649     RANDOM_EXPIRED_TIMEOUT = timeouts[rnd.nextInt(3)];
650     TimeUnit[] timeUnits = TimeUnit.values();
651     RANDOM_TIMEUNIT = timeUnits[rnd.nextInt(timeUnits.length)];
652     }
653    
654     /**
655     * Returns a timeout for use when any value at all will do.
656     */
657     static long randomTimeout() { return RANDOM_TIMEOUT; }
658    
659     /**
660     * Returns a timeout that means "no waiting", i.e. not positive.
661     */
662     static long randomExpiredTimeout() { return RANDOM_EXPIRED_TIMEOUT; }
663    
664     /**
665     * Returns a random non-null TimeUnit.
666     */
667     static TimeUnit randomTimeUnit() { return RANDOM_TIMEUNIT; }
668    
669 dl 1.2 /**
670 jsr166 1.181 * Returns the shortest timed delay. This can be scaled up for
671 jsr166 1.185 * slow machines using the jsr166.delay.factor system property,
672 jsr166 1.187 * or via jtreg's -timeoutFactor: flag.
673 jsr166 1.185 * http://openjdk.java.net/jtreg/command-help.html
674 jsr166 1.27 */
675 dl 1.2 protected long getShortDelay() {
676 jsr166 1.189 return (long) (50 * delayFactor);
677 dl 1.2 }
678    
679     /**
680 jsr166 1.27 * Sets delays as multiples of SHORT_DELAY.
681 dl 1.2 */
682 jsr166 1.43 protected void setDelays() {
683 dl 1.2 SHORT_DELAY_MS = getShortDelay();
684 jsr166 1.53 SMALL_DELAY_MS = SHORT_DELAY_MS * 5;
685 dl 1.2 MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
686 jsr166 1.71 LONG_DELAY_MS = SHORT_DELAY_MS * 200;
687 dl 1.2 }
688    
689 jsr166 1.223 private static final long TIMEOUT_DELAY_MS
690     = (long) (12.0 * Math.cbrt(delayFactor));
691    
692 dl 1.1 /**
693 jsr166 1.223 * Returns a timeout in milliseconds to be used in tests that verify
694     * that operations block or time out. We want this to be longer
695     * than the OS scheduling quantum, but not too long, so don't scale
696     * linearly with delayFactor; we use "crazy" cube root instead.
697 jsr166 1.81 */
698 jsr166 1.223 static long timeoutMillis() {
699     return TIMEOUT_DELAY_MS;
700 jsr166 1.81 }
701    
702     /**
703 jsr166 1.135 * Returns a new Date instance representing a time at least
704     * delayMillis milliseconds in the future.
705 jsr166 1.81 */
706     Date delayedDate(long delayMillis) {
707 jsr166 1.135 // Add 1 because currentTimeMillis is known to round into the past.
708     return new Date(System.currentTimeMillis() + delayMillis + 1);
709 jsr166 1.81 }
710    
711     /**
712 jsr166 1.53 * The first exception encountered if any threadAssertXXX method fails.
713 dl 1.1 */
714 jsr166 1.53 private final AtomicReference<Throwable> threadFailure
715 jsr166 1.216 = new AtomicReference<>(null);
716 dl 1.1
717     /**
718 jsr166 1.53 * Records an exception so that it can be rethrown later in the test
719     * harness thread, triggering a test case failure. Only the first
720     * failure is recorded; subsequent calls to this method from within
721     * the same test have no effect.
722 dl 1.1 */
723 jsr166 1.53 public void threadRecordFailure(Throwable t) {
724 jsr166 1.158 System.err.println(t);
725 jsr166 1.156 dumpTestThreads();
726 jsr166 1.53 threadFailure.compareAndSet(null, t);
727     }
728    
729 jsr166 1.27 public void setUp() {
730 dl 1.2 setDelays();
731 dl 1.1 }
732    
733 jsr166 1.146 void tearDownFail(String format, Object... args) {
734     String msg = toString() + ": " + String.format(format, args);
735     System.err.println(msg);
736 jsr166 1.156 dumpTestThreads();
737 jsr166 1.239 throw new AssertionError(msg);
738 jsr166 1.146 }
739    
740 dl 1.1 /**
741 jsr166 1.85 * Extra checks that get done for all test cases.
742     *
743 jsr166 1.53 * Triggers test case failure if any thread assertions have failed,
744     * by rethrowing, in the test harness thread, any exception recorded
745     * earlier by threadRecordFailure.
746 jsr166 1.85 *
747     * Triggers test case failure if interrupt status is set in the main thread.
748 jsr166 1.53 */
749     public void tearDown() throws Exception {
750 jsr166 1.70 Throwable t = threadFailure.getAndSet(null);
751 jsr166 1.53 if (t != null) {
752     if (t instanceof Error)
753     throw (Error) t;
754     else if (t instanceof RuntimeException)
755     throw (RuntimeException) t;
756     else if (t instanceof Exception)
757     throw (Exception) t;
758 jsr166 1.239 else
759     throw new AssertionError(t.toString(), t);
760 jsr166 1.53 }
761 jsr166 1.85
762     if (Thread.interrupted())
763 jsr166 1.146 tearDownFail("interrupt status set in main thread");
764 jsr166 1.100
765     checkForkJoinPoolThreadLeaks();
766 dl 1.1 }
767    
768 dl 1.5 /**
769 jsr166 1.164 * Finds missing PoolCleaners
770 jsr166 1.100 */
771     void checkForkJoinPoolThreadLeaks() throws InterruptedException {
772 jsr166 1.146 Thread[] survivors = new Thread[7];
773 jsr166 1.100 int count = Thread.enumerate(survivors);
774     for (int i = 0; i < count; i++) {
775     Thread thread = survivors[i];
776     String name = thread.getName();
777     if (name.startsWith("ForkJoinPool-")) {
778     // give thread some time to terminate
779     thread.join(LONG_DELAY_MS);
780 jsr166 1.146 if (thread.isAlive())
781     tearDownFail("Found leaked ForkJoinPool thread thread=%s",
782     thread);
783 jsr166 1.100 }
784     }
785 jsr166 1.146
786     if (!ForkJoinPool.commonPool()
787     .awaitQuiescence(LONG_DELAY_MS, MILLISECONDS))
788     tearDownFail("ForkJoin common pool thread stuck");
789 jsr166 1.100 }
790 jsr166 1.101
791 jsr166 1.100 /**
792 jsr166 1.53 * Just like fail(reason), but additionally recording (using
793 jsr166 1.239 * threadRecordFailure) any AssertionError thrown, so that the
794     * current testcase will fail.
795 jsr166 1.27 */
796 dl 1.1 public void threadFail(String reason) {
797 jsr166 1.53 try {
798     fail(reason);
799 jsr166 1.239 } catch (AssertionError fail) {
800     threadRecordFailure(fail);
801     throw fail;
802 jsr166 1.53 }
803 dl 1.1 }
804    
805 dl 1.5 /**
806 jsr166 1.53 * Just like assertTrue(b), but additionally recording (using
807 jsr166 1.239 * threadRecordFailure) any AssertionError thrown, so that the
808     * current testcase will fail.
809 jsr166 1.27 */
810 dl 1.1 public void threadAssertTrue(boolean b) {
811 jsr166 1.53 try {
812 dl 1.1 assertTrue(b);
813 jsr166 1.239 } catch (AssertionError fail) {
814     threadRecordFailure(fail);
815     throw fail;
816 dl 1.1 }
817     }
818 dl 1.5
819     /**
820 jsr166 1.53 * Just like assertFalse(b), but additionally recording (using
821 jsr166 1.239 * threadRecordFailure) any AssertionError thrown, so that the
822     * current testcase will fail.
823 jsr166 1.27 */
824 dl 1.1 public void threadAssertFalse(boolean b) {
825 jsr166 1.53 try {
826 dl 1.1 assertFalse(b);
827 jsr166 1.239 } catch (AssertionError fail) {
828     threadRecordFailure(fail);
829     throw fail;
830 dl 1.1 }
831     }
832 dl 1.5
833     /**
834 jsr166 1.53 * Just like assertNull(x), but additionally recording (using
835 jsr166 1.239 * threadRecordFailure) any AssertionError thrown, so that the
836     * current testcase will fail.
837 jsr166 1.27 */
838 dl 1.1 public void threadAssertNull(Object x) {
839 jsr166 1.53 try {
840 dl 1.1 assertNull(x);
841 jsr166 1.239 } catch (AssertionError fail) {
842     threadRecordFailure(fail);
843     throw fail;
844 dl 1.1 }
845     }
846 dl 1.5
847     /**
848 jsr166 1.53 * Just like assertEquals(x, y), but additionally recording (using
849 jsr166 1.239 * threadRecordFailure) any AssertionError thrown, so that the
850     * current testcase will fail.
851 jsr166 1.27 */
852 dl 1.1 public void threadAssertEquals(long x, long y) {
853 jsr166 1.53 try {
854 dl 1.1 assertEquals(x, y);
855 jsr166 1.239 } catch (AssertionError fail) {
856     threadRecordFailure(fail);
857     throw fail;
858 dl 1.1 }
859     }
860 dl 1.5
861     /**
862 jsr166 1.53 * Just like assertEquals(x, y), but additionally recording (using
863 jsr166 1.239 * threadRecordFailure) any AssertionError thrown, so that the
864     * current testcase will fail.
865 jsr166 1.27 */
866 dl 1.1 public void threadAssertEquals(Object x, Object y) {
867 jsr166 1.53 try {
868 dl 1.1 assertEquals(x, y);
869 jsr166 1.239 } catch (AssertionError fail) {
870 jsr166 1.129 threadRecordFailure(fail);
871     throw fail;
872     } catch (Throwable fail) {
873     threadUnexpectedException(fail);
874 dl 1.1 }
875     }
876    
877 dl 1.5 /**
878 jsr166 1.53 * Just like assertSame(x, y), but additionally recording (using
879 jsr166 1.239 * threadRecordFailure) any AssertionError thrown, so that the
880     * current testcase will fail.
881 jsr166 1.52 */
882     public void threadAssertSame(Object x, Object y) {
883 jsr166 1.53 try {
884 jsr166 1.52 assertSame(x, y);
885 jsr166 1.239 } catch (AssertionError fail) {
886 jsr166 1.129 threadRecordFailure(fail);
887     throw fail;
888 jsr166 1.52 }
889     }
890    
891     /**
892 jsr166 1.53 * Calls threadFail with message "should throw exception".
893 jsr166 1.33 */
894 dl 1.3 public void threadShouldThrow() {
895 jsr166 1.53 threadFail("should throw exception");
896 dl 1.3 }
897    
898 dl 1.5 /**
899 jsr166 1.53 * Calls threadFail with message "should throw" + exceptionName.
900 jsr166 1.40 */
901     public void threadShouldThrow(String exceptionName) {
902 jsr166 1.53 threadFail("should throw " + exceptionName);
903 dl 1.3 }
904    
905 dl 1.31 /**
906 jsr166 1.57 * Records the given exception using {@link #threadRecordFailure},
907 jsr166 1.239 * then rethrows the exception, wrapping it in an AssertionError
908     * if necessary.
909 dl 1.31 */
910 jsr166 1.53 public void threadUnexpectedException(Throwable t) {
911     threadRecordFailure(t);
912     t.printStackTrace();
913     if (t instanceof RuntimeException)
914     throw (RuntimeException) t;
915     else if (t instanceof Error)
916     throw (Error) t;
917 jsr166 1.239 else
918     throw new AssertionError("unexpected exception: " + t, t);
919 dl 1.31 }
920 dl 1.3
921 dl 1.1 /**
922 jsr166 1.81 * Delays, via Thread.sleep, for the given millisecond delay, but
923 dl 1.76 * if the sleep is shorter than specified, may re-sleep or yield
924 jsr166 1.163 * until time elapses. Ensures that the given time, as measured
925     * by System.nanoTime(), has elapsed.
926 dl 1.76 */
927 jsr166 1.81 static void delay(long millis) throws InterruptedException {
928 jsr166 1.163 long nanos = millis * (1000 * 1000);
929     final long wakeupTime = System.nanoTime() + nanos;
930     do {
931 jsr166 1.80 if (millis > 0L)
932     Thread.sleep(millis);
933 dl 1.76 else // too short to sleep
934     Thread.yield();
935 jsr166 1.163 nanos = wakeupTime - System.nanoTime();
936     millis = nanos / (1000 * 1000);
937     } while (nanos >= 0L);
938 dl 1.76 }
939    
940     /**
941 jsr166 1.149 * Allows use of try-with-resources with per-test thread pools.
942     */
943 jsr166 1.160 class PoolCleaner implements AutoCloseable {
944     private final ExecutorService pool;
945     public PoolCleaner(ExecutorService pool) { this.pool = pool; }
946 jsr166 1.149 public void close() { joinPool(pool); }
947     }
948    
949 jsr166 1.166 /**
950     * An extension of PoolCleaner that has an action to release the pool.
951     */
952     class PoolCleanerWithReleaser extends PoolCleaner {
953     private final Runnable releaser;
954     public PoolCleanerWithReleaser(ExecutorService pool, Runnable releaser) {
955     super(pool);
956     this.releaser = releaser;
957     }
958     public void close() {
959     try {
960     releaser.run();
961     } finally {
962     super.close();
963     }
964     }
965     }
966    
967 jsr166 1.160 PoolCleaner cleaner(ExecutorService pool) {
968     return new PoolCleaner(pool);
969 jsr166 1.159 }
970    
971 jsr166 1.166 PoolCleaner cleaner(ExecutorService pool, Runnable releaser) {
972     return new PoolCleanerWithReleaser(pool, releaser);
973     }
974    
975     PoolCleaner cleaner(ExecutorService pool, CountDownLatch latch) {
976     return new PoolCleanerWithReleaser(pool, releaser(latch));
977     }
978    
979     Runnable releaser(final CountDownLatch latch) {
980     return new Runnable() { public void run() {
981     do { latch.countDown(); }
982     while (latch.getCount() > 0);
983     }};
984     }
985    
986 jsr166 1.185 PoolCleaner cleaner(ExecutorService pool, AtomicBoolean flag) {
987     return new PoolCleanerWithReleaser(pool, releaser(flag));
988     }
989    
990     Runnable releaser(final AtomicBoolean flag) {
991     return new Runnable() { public void run() { flag.set(true); }};
992     }
993    
994 jsr166 1.149 /**
995 jsr166 1.53 * Waits out termination of a thread pool or fails doing so.
996 dl 1.1 */
997 jsr166 1.158 void joinPool(ExecutorService pool) {
998 dl 1.1 try {
999 jsr166 1.139 pool.shutdown();
1000 jsr166 1.158 if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS)) {
1001     try {
1002     threadFail("ExecutorService " + pool +
1003     " did not terminate in a timely manner");
1004     } finally {
1005     // last resort, for the benefit of subsequent tests
1006     pool.shutdownNow();
1007 jsr166 1.167 pool.awaitTermination(MEDIUM_DELAY_MS, MILLISECONDS);
1008 jsr166 1.158 }
1009     }
1010 jsr166 1.33 } catch (SecurityException ok) {
1011 dl 1.22 // Allowed in case test doesn't have privs
1012 jsr166 1.128 } catch (InterruptedException fail) {
1013 jsr166 1.158 threadFail("Unexpected InterruptedException");
1014 dl 1.1 }
1015     }
1016    
1017 jsr166 1.197 /**
1018     * Like Runnable, but with the freedom to throw anything.
1019     * junit folks had the same idea:
1020     * http://junit.org/junit5/docs/snapshot/api/org/junit/gen5/api/Executable.html
1021     */
1022 jsr166 1.141 interface Action { public void run() throws Throwable; }
1023 jsr166 1.139
1024     /**
1025 jsr166 1.141 * Runs all the given actions in parallel, failing if any fail.
1026 jsr166 1.139 * Useful for running multiple variants of tests that are
1027     * necessarily individually slow because they must block.
1028     */
1029 jsr166 1.141 void testInParallel(Action ... actions) {
1030 jsr166 1.160 ExecutorService pool = Executors.newCachedThreadPool();
1031     try (PoolCleaner cleaner = cleaner(pool)) {
1032 jsr166 1.141 ArrayList<Future<?>> futures = new ArrayList<>(actions.length);
1033     for (final Action action : actions)
1034 jsr166 1.139 futures.add(pool.submit(new CheckedRunnable() {
1035 jsr166 1.141 public void realRun() throws Throwable { action.run();}}));
1036 jsr166 1.139 for (Future<?> future : futures)
1037     try {
1038     assertNull(future.get(LONG_DELAY_MS, MILLISECONDS));
1039     } catch (ExecutionException ex) {
1040     threadUnexpectedException(ex.getCause());
1041     } catch (Exception ex) {
1042     threadUnexpectedException(ex);
1043     }
1044     }
1045     }
1046    
1047 jsr166 1.78 /**
1048 jsr166 1.156 * A debugging tool to print stack traces of most threads, as jstack does.
1049 jsr166 1.150 * Uninteresting threads are filtered out.
1050 jsr166 1.95 */
1051 jsr166 1.156 static void dumpTestThreads() {
1052 jsr166 1.195 SecurityManager sm = System.getSecurityManager();
1053     if (sm != null) {
1054     try {
1055     System.setSecurityManager(null);
1056     } catch (SecurityException giveUp) {
1057     return;
1058     }
1059     }
1060    
1061 jsr166 1.150 ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
1062     System.err.println("------ stacktrace dump start ------");
1063     for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) {
1064 jsr166 1.203 final String name = info.getThreadName();
1065     String lockName;
1066 jsr166 1.150 if ("Signal Dispatcher".equals(name))
1067     continue;
1068     if ("Reference Handler".equals(name)
1069 jsr166 1.203 && (lockName = info.getLockName()) != null
1070     && lockName.startsWith("java.lang.ref.Reference$Lock"))
1071 jsr166 1.150 continue;
1072     if ("Finalizer".equals(name)
1073 jsr166 1.203 && (lockName = info.getLockName()) != null
1074     && lockName.startsWith("java.lang.ref.ReferenceQueue$Lock"))
1075 jsr166 1.150 continue;
1076 jsr166 1.156 if ("checkForWedgedTest".equals(name))
1077     continue;
1078 jsr166 1.96 System.err.print(info);
1079 jsr166 1.150 }
1080     System.err.println("------ stacktrace dump end ------");
1081 jsr166 1.195
1082     if (sm != null) System.setSecurityManager(sm);
1083 jsr166 1.95 }
1084    
1085     /**
1086 jsr166 1.224 * Checks that thread eventually enters the expected blocked thread state.
1087     */
1088     void assertThreadBlocks(Thread thread, Thread.State expected) {
1089 jsr166 1.228 // always sleep at least 1 ms, with high probability avoiding
1090     // transitory states
1091 jsr166 1.225 for (long retries = LONG_DELAY_MS * 3 / 4; retries-->0; ) {
1092 jsr166 1.224 try { delay(1); }
1093     catch (InterruptedException fail) {
1094 jsr166 1.240 throw new AssertionError("Unexpected InterruptedException", fail);
1095 jsr166 1.224 }
1096     Thread.State s = thread.getState();
1097     if (s == expected)
1098     return;
1099     else if (s == Thread.State.TERMINATED)
1100     fail("Unexpected thread termination");
1101     }
1102     fail("timed out waiting for thread to enter thread state " + expected);
1103     }
1104    
1105     /**
1106 jsr166 1.83 * Checks that future.get times out, with the default timeout of
1107     * {@code timeoutMillis()}.
1108     */
1109     void assertFutureTimesOut(Future future) {
1110     assertFutureTimesOut(future, timeoutMillis());
1111     }
1112    
1113     /**
1114     * Checks that future.get times out, with the given millisecond timeout.
1115     */
1116     void assertFutureTimesOut(Future future, long timeoutMillis) {
1117     long startTime = System.nanoTime();
1118     try {
1119     future.get(timeoutMillis, MILLISECONDS);
1120     shouldThrow();
1121     } catch (TimeoutException success) {
1122 jsr166 1.128 } catch (Exception fail) {
1123     threadUnexpectedException(fail);
1124 jsr166 1.83 } finally { future.cancel(true); }
1125     assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
1126     }
1127    
1128     /**
1129 jsr166 1.53 * Fails with message "should throw exception".
1130 jsr166 1.27 */
1131 dl 1.3 public void shouldThrow() {
1132     fail("Should throw exception");
1133     }
1134    
1135 dl 1.5 /**
1136 jsr166 1.53 * Fails with message "should throw " + exceptionName.
1137 jsr166 1.40 */
1138     public void shouldThrow(String exceptionName) {
1139     fail("Should throw " + exceptionName);
1140     }
1141    
1142     /**
1143 jsr166 1.222 * The maximum number of consecutive spurious wakeups we should
1144     * tolerate (from APIs like LockSupport.park) before failing a test.
1145     */
1146     static final int MAX_SPURIOUS_WAKEUPS = 10;
1147    
1148     /**
1149 dl 1.1 * The number of elements to place in collections, arrays, etc.
1150     */
1151 jsr166 1.45 public static final int SIZE = 20;
1152 dl 1.1
1153     // Some convenient Integer constants
1154    
1155 jsr166 1.47 public static final Integer zero = new Integer(0);
1156     public static final Integer one = new Integer(1);
1157     public static final Integer two = new Integer(2);
1158     public static final Integer three = new Integer(3);
1159 jsr166 1.45 public static final Integer four = new Integer(4);
1160     public static final Integer five = new Integer(5);
1161 jsr166 1.47 public static final Integer six = new Integer(6);
1162 jsr166 1.45 public static final Integer seven = new Integer(7);
1163     public static final Integer eight = new Integer(8);
1164 jsr166 1.47 public static final Integer nine = new Integer(9);
1165 jsr166 1.45 public static final Integer m1 = new Integer(-1);
1166     public static final Integer m2 = new Integer(-2);
1167     public static final Integer m3 = new Integer(-3);
1168 jsr166 1.47 public static final Integer m4 = new Integer(-4);
1169     public static final Integer m5 = new Integer(-5);
1170     public static final Integer m6 = new Integer(-6);
1171 jsr166 1.45 public static final Integer m10 = new Integer(-10);
1172 dl 1.7
1173     /**
1174 jsr166 1.49 * Runs Runnable r with a security policy that permits precisely
1175     * the specified permissions. If there is no current security
1176     * manager, the runnable is run twice, both with and without a
1177     * security manager. We require that any security manager permit
1178     * getPolicy/setPolicy.
1179     */
1180     public void runWithPermissions(Runnable r, Permission... permissions) {
1181     SecurityManager sm = System.getSecurityManager();
1182     if (sm == null) {
1183     r.run();
1184 jsr166 1.93 }
1185     runWithSecurityManagerWithPermissions(r, permissions);
1186     }
1187    
1188     /**
1189     * Runs Runnable r with a security policy that permits precisely
1190     * the specified permissions. If there is no current security
1191     * manager, a temporary one is set for the duration of the
1192     * Runnable. We require that any security manager permit
1193     * getPolicy/setPolicy.
1194     */
1195     public void runWithSecurityManagerWithPermissions(Runnable r,
1196     Permission... permissions) {
1197     SecurityManager sm = System.getSecurityManager();
1198     if (sm == null) {
1199 jsr166 1.49 Policy savedPolicy = Policy.getPolicy();
1200     try {
1201     Policy.setPolicy(permissivePolicy());
1202     System.setSecurityManager(new SecurityManager());
1203 jsr166 1.93 runWithSecurityManagerWithPermissions(r, permissions);
1204 jsr166 1.49 } finally {
1205     System.setSecurityManager(null);
1206     Policy.setPolicy(savedPolicy);
1207     }
1208     } else {
1209     Policy savedPolicy = Policy.getPolicy();
1210     AdjustablePolicy policy = new AdjustablePolicy(permissions);
1211     Policy.setPolicy(policy);
1212    
1213     try {
1214     r.run();
1215     } finally {
1216     policy.addPermission(new SecurityPermission("setPolicy"));
1217     Policy.setPolicy(savedPolicy);
1218     }
1219     }
1220     }
1221    
1222     /**
1223     * Runs a runnable without any permissions.
1224     */
1225     public void runWithoutPermissions(Runnable r) {
1226     runWithPermissions(r);
1227     }
1228    
1229     /**
1230 dl 1.7 * A security policy where new permissions can be dynamically added
1231     * or all cleared.
1232     */
1233 jsr166 1.45 public static class AdjustablePolicy extends java.security.Policy {
1234 dl 1.7 Permissions perms = new Permissions();
1235 jsr166 1.49 AdjustablePolicy(Permission... permissions) {
1236     for (Permission permission : permissions)
1237     perms.add(permission);
1238     }
1239 dl 1.7 void addPermission(Permission perm) { perms.add(perm); }
1240     void clearPermissions() { perms = new Permissions(); }
1241 jsr166 1.42 public PermissionCollection getPermissions(CodeSource cs) {
1242     return perms;
1243     }
1244     public PermissionCollection getPermissions(ProtectionDomain pd) {
1245     return perms;
1246     }
1247     public boolean implies(ProtectionDomain pd, Permission p) {
1248     return perms.implies(p);
1249     }
1250     public void refresh() {}
1251 jsr166 1.93 public String toString() {
1252 jsr166 1.216 List<Permission> ps = new ArrayList<>();
1253 jsr166 1.93 for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
1254     ps.add(e.nextElement());
1255     return "AdjustablePolicy with permissions " + ps;
1256     }
1257 dl 1.7 }
1258 dl 1.1
1259 jsr166 1.38 /**
1260 jsr166 1.49 * Returns a policy containing all the permissions we ever need.
1261     */
1262     public static Policy permissivePolicy() {
1263     return new AdjustablePolicy
1264     // Permissions j.u.c. needs directly
1265     (new RuntimePermission("modifyThread"),
1266     new RuntimePermission("getClassLoader"),
1267     new RuntimePermission("setContextClassLoader"),
1268     // Permissions needed to change permissions!
1269     new SecurityPermission("getPolicy"),
1270     new SecurityPermission("setPolicy"),
1271     new RuntimePermission("setSecurityManager"),
1272     // Permissions needed by the junit test harness
1273     new RuntimePermission("accessDeclaredMembers"),
1274     new PropertyPermission("*", "read"),
1275     new java.io.FilePermission("<<ALL FILES>>", "read"));
1276     }
1277    
1278     /**
1279 jsr166 1.60 * Sleeps until the given time has elapsed.
1280 jsr166 1.239 * Throws AssertionError if interrupted.
1281 jsr166 1.60 */
1282 jsr166 1.201 static void sleep(long millis) {
1283 jsr166 1.60 try {
1284 dl 1.76 delay(millis);
1285 jsr166 1.128 } catch (InterruptedException fail) {
1286 jsr166 1.239 throw new AssertionError("Unexpected InterruptedException", fail);
1287 jsr166 1.60 }
1288     }
1289    
1290     /**
1291 jsr166 1.88 * Spin-waits up to the specified number of milliseconds for the given
1292 jsr166 1.65 * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1293     */
1294     void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
1295 jsr166 1.199 long startTime = 0L;
1296 jsr166 1.65 for (;;) {
1297     Thread.State s = thread.getState();
1298     if (s == Thread.State.BLOCKED ||
1299     s == Thread.State.WAITING ||
1300 jsr166 1.67 s == Thread.State.TIMED_WAITING)
1301 jsr166 1.65 return;
1302 jsr166 1.67 else if (s == Thread.State.TERMINATED)
1303     fail("Unexpected thread termination");
1304 jsr166 1.199 else if (startTime == 0L)
1305     startTime = System.nanoTime();
1306 jsr166 1.88 else if (millisElapsedSince(startTime) > timeoutMillis) {
1307 jsr166 1.67 threadAssertTrue(thread.isAlive());
1308 jsr166 1.219 fail("timed out waiting for thread to enter wait state");
1309 jsr166 1.67 }
1310 jsr166 1.65 Thread.yield();
1311     }
1312     }
1313    
1314     /**
1315 jsr166 1.219 * Spin-waits up to the specified number of milliseconds for the given
1316     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING,
1317     * and additionally satisfy the given condition.
1318     */
1319     void waitForThreadToEnterWaitState(
1320     Thread thread, long timeoutMillis, Callable<Boolean> waitingForGodot) {
1321     long startTime = 0L;
1322     for (;;) {
1323     Thread.State s = thread.getState();
1324     if (s == Thread.State.BLOCKED ||
1325     s == Thread.State.WAITING ||
1326     s == Thread.State.TIMED_WAITING) {
1327     try {
1328     if (waitingForGodot.call())
1329     return;
1330     } catch (Throwable fail) { threadUnexpectedException(fail); }
1331     }
1332     else if (s == Thread.State.TERMINATED)
1333     fail("Unexpected thread termination");
1334     else if (startTime == 0L)
1335     startTime = System.nanoTime();
1336     else if (millisElapsedSince(startTime) > timeoutMillis) {
1337     threadAssertTrue(thread.isAlive());
1338     fail("timed out waiting for thread to enter wait state");
1339     }
1340     Thread.yield();
1341     }
1342     }
1343    
1344     /**
1345     * Spin-waits up to LONG_DELAY_MS milliseconds for the given thread to
1346     * enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1347 jsr166 1.75 */
1348     void waitForThreadToEnterWaitState(Thread thread) {
1349     waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
1350     }
1351    
1352     /**
1353 jsr166 1.219 * Spin-waits up to LONG_DELAY_MS milliseconds for the given thread to
1354     * enter a wait state: BLOCKED, WAITING, or TIMED_WAITING,
1355     * and additionally satisfy the given condition.
1356     */
1357     void waitForThreadToEnterWaitState(
1358     Thread thread, Callable<Boolean> waitingForGodot) {
1359     waitForThreadToEnterWaitState(thread, LONG_DELAY_MS, waitingForGodot);
1360     }
1361    
1362     /**
1363 jsr166 1.66 * Returns the number of milliseconds since time given by
1364     * startNanoTime, which must have been previously returned from a
1365 jsr166 1.124 * call to {@link System#nanoTime()}.
1366 jsr166 1.66 */
1367 jsr166 1.117 static long millisElapsedSince(long startNanoTime) {
1368 jsr166 1.66 return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
1369     }
1370 jsr166 1.68
1371 jsr166 1.120 // void assertTerminatesPromptly(long timeoutMillis, Runnable r) {
1372     // long startTime = System.nanoTime();
1373     // try {
1374     // r.run();
1375     // } catch (Throwable fail) { threadUnexpectedException(fail); }
1376     // if (millisElapsedSince(startTime) > timeoutMillis/2)
1377 jsr166 1.239 // throw new AssertionError("did not return promptly");
1378 jsr166 1.120 // }
1379    
1380     // void assertTerminatesPromptly(Runnable r) {
1381     // assertTerminatesPromptly(LONG_DELAY_MS/2, r);
1382     // }
1383    
1384     /**
1385     * Checks that timed f.get() returns the expected value, and does not
1386     * wait for the timeout to elapse before returning.
1387     */
1388     <T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) {
1389     long startTime = System.nanoTime();
1390     try {
1391     assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
1392     } catch (Throwable fail) { threadUnexpectedException(fail); }
1393     if (millisElapsedSince(startTime) > timeoutMillis/2)
1394 jsr166 1.239 throw new AssertionError("timed get did not return promptly");
1395 jsr166 1.120 }
1396    
1397     <T> void checkTimedGet(Future<T> f, T expectedValue) {
1398     checkTimedGet(f, expectedValue, LONG_DELAY_MS);
1399     }
1400    
1401 jsr166 1.66 /**
1402 jsr166 1.58 * Returns a new started daemon Thread running the given runnable.
1403 jsr166 1.38 */
1404     Thread newStartedThread(Runnable runnable) {
1405     Thread t = new Thread(runnable);
1406 jsr166 1.58 t.setDaemon(true);
1407 jsr166 1.38 t.start();
1408     return t;
1409     }
1410 dl 1.1
1411 jsr166 1.59 /**
1412     * Waits for the specified time (in milliseconds) for the thread
1413     * to terminate (using {@link Thread#join(long)}), else interrupts
1414     * the thread (in the hope that it may terminate later) and fails.
1415     */
1416     void awaitTermination(Thread t, long timeoutMillis) {
1417     try {
1418     t.join(timeoutMillis);
1419 jsr166 1.128 } catch (InterruptedException fail) {
1420     threadUnexpectedException(fail);
1421 jsr166 1.59 } finally {
1422 jsr166 1.83 if (t.getState() != Thread.State.TERMINATED) {
1423 jsr166 1.59 t.interrupt();
1424 jsr166 1.177 threadFail("timed out waiting for thread to terminate");
1425 jsr166 1.59 }
1426     }
1427     }
1428    
1429 jsr166 1.75 /**
1430     * Waits for LONG_DELAY_MS milliseconds for the thread to
1431     * terminate (using {@link Thread#join(long)}), else interrupts
1432     * the thread (in the hope that it may terminate later) and fails.
1433     */
1434     void awaitTermination(Thread t) {
1435     awaitTermination(t, LONG_DELAY_MS);
1436     }
1437    
1438 dl 1.1 // Some convenient Runnable classes
1439    
1440 jsr166 1.45 public abstract class CheckedRunnable implements Runnable {
1441     protected abstract void realRun() throws Throwable;
1442 jsr166 1.35
1443     public final void run() {
1444     try {
1445     realRun();
1446 jsr166 1.128 } catch (Throwable fail) {
1447     threadUnexpectedException(fail);
1448 jsr166 1.35 }
1449     }
1450     }
1451    
1452 jsr166 1.45 public abstract class ThreadShouldThrow extends Thread {
1453     protected abstract void realRun() throws Throwable;
1454 jsr166 1.40
1455     final Class<?> exceptionClass;
1456    
1457     <T extends Throwable> ThreadShouldThrow(Class<T> exceptionClass) {
1458     this.exceptionClass = exceptionClass;
1459     }
1460    
1461     public final void run() {
1462     try {
1463     realRun();
1464     threadShouldThrow(exceptionClass.getSimpleName());
1465     } catch (Throwable t) {
1466     if (! exceptionClass.isInstance(t))
1467     threadUnexpectedException(t);
1468     }
1469     }
1470     }
1471    
1472 jsr166 1.45 public abstract class CheckedInterruptedRunnable implements Runnable {
1473     protected abstract void realRun() throws Throwable;
1474 jsr166 1.35
1475     public final void run() {
1476     try {
1477     realRun();
1478 jsr166 1.40 threadShouldThrow("InterruptedException");
1479 jsr166 1.35 } catch (InterruptedException success) {
1480 jsr166 1.81 threadAssertFalse(Thread.interrupted());
1481 jsr166 1.128 } catch (Throwable fail) {
1482     threadUnexpectedException(fail);
1483 jsr166 1.35 }
1484     }
1485     }
1486    
1487 jsr166 1.45 public abstract class CheckedCallable<T> implements Callable<T> {
1488     protected abstract T realCall() throws Throwable;
1489 jsr166 1.35
1490     public final T call() {
1491     try {
1492     return realCall();
1493 jsr166 1.128 } catch (Throwable fail) {
1494     threadUnexpectedException(fail);
1495 jsr166 1.53 return null;
1496 jsr166 1.35 }
1497 jsr166 1.40 }
1498     }
1499    
1500 jsr166 1.53 public abstract class CheckedInterruptedCallable<T>
1501     implements Callable<T> {
1502 jsr166 1.45 protected abstract T realCall() throws Throwable;
1503 jsr166 1.40
1504     public final T call() {
1505     try {
1506     T result = realCall();
1507     threadShouldThrow("InterruptedException");
1508     return result;
1509     } catch (InterruptedException success) {
1510 jsr166 1.81 threadAssertFalse(Thread.interrupted());
1511 jsr166 1.128 } catch (Throwable fail) {
1512     threadUnexpectedException(fail);
1513 jsr166 1.40 }
1514     return null;
1515 jsr166 1.35 }
1516     }
1517    
1518 jsr166 1.45 public static class NoOpRunnable implements Runnable {
1519 dl 1.1 public void run() {}
1520     }
1521    
1522 jsr166 1.45 public static class NoOpCallable implements Callable {
1523 dl 1.1 public Object call() { return Boolean.TRUE; }
1524 dl 1.10 }
1525    
1526 jsr166 1.45 public static final String TEST_STRING = "a test string";
1527 dl 1.10
1528 jsr166 1.45 public static class StringTask implements Callable<String> {
1529 jsr166 1.144 final String value;
1530     public StringTask() { this(TEST_STRING); }
1531     public StringTask(String value) { this.value = value; }
1532     public String call() { return value; }
1533 dl 1.10 }
1534    
1535 jsr166 1.48 public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
1536     return new CheckedCallable<String>() {
1537 jsr166 1.64 protected String realCall() {
1538 jsr166 1.48 try {
1539     latch.await();
1540     } catch (InterruptedException quittingTime) {}
1541     return TEST_STRING;
1542     }};
1543     }
1544    
1545 jsr166 1.148 public Runnable countDowner(final CountDownLatch latch) {
1546     return new CheckedRunnable() {
1547     public void realRun() throws InterruptedException {
1548     latch.countDown();
1549     }};
1550     }
1551    
1552 jsr166 1.161 class LatchAwaiter extends CheckedRunnable {
1553 jsr166 1.162 static final int NEW = 0;
1554     static final int RUNNING = 1;
1555     static final int DONE = 2;
1556 jsr166 1.161 final CountDownLatch latch;
1557     int state = NEW;
1558     LatchAwaiter(CountDownLatch latch) { this.latch = latch; }
1559     public void realRun() throws InterruptedException {
1560     state = 1;
1561     await(latch);
1562     state = 2;
1563     }
1564     }
1565 jsr166 1.162
1566 jsr166 1.161 public LatchAwaiter awaiter(CountDownLatch latch) {
1567     return new LatchAwaiter(latch);
1568 jsr166 1.73 }
1569    
1570 jsr166 1.188 public void await(CountDownLatch latch, long timeoutMillis) {
1571 jsr166 1.79 try {
1572 jsr166 1.188 if (!latch.await(timeoutMillis, MILLISECONDS))
1573 jsr166 1.176 fail("timed out waiting for CountDownLatch for "
1574 jsr166 1.188 + (timeoutMillis/1000) + " sec");
1575 jsr166 1.128 } catch (Throwable fail) {
1576     threadUnexpectedException(fail);
1577 jsr166 1.79 }
1578     }
1579    
1580 jsr166 1.188 public void await(CountDownLatch latch) {
1581     await(latch, LONG_DELAY_MS);
1582     }
1583    
1584 jsr166 1.89 public void await(Semaphore semaphore) {
1585     try {
1586 jsr166 1.176 if (!semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS))
1587     fail("timed out waiting for Semaphore for "
1588     + (LONG_DELAY_MS/1000) + " sec");
1589 jsr166 1.128 } catch (Throwable fail) {
1590     threadUnexpectedException(fail);
1591 jsr166 1.89 }
1592     }
1593    
1594 jsr166 1.226 public void await(CyclicBarrier barrier) {
1595     try {
1596     barrier.await(LONG_DELAY_MS, MILLISECONDS);
1597     } catch (Throwable fail) {
1598     threadUnexpectedException(fail);
1599     }
1600     }
1601    
1602 jsr166 1.81 // /**
1603     // * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1604     // */
1605     // public void await(AtomicBoolean flag) {
1606     // await(flag, LONG_DELAY_MS);
1607     // }
1608    
1609     // /**
1610     // * Spin-waits up to the specified timeout until flag becomes true.
1611     // */
1612     // public void await(AtomicBoolean flag, long timeoutMillis) {
1613     // long startTime = System.nanoTime();
1614     // while (!flag.get()) {
1615     // if (millisElapsedSince(startTime) > timeoutMillis)
1616 jsr166 1.239 // throw new AssertionError("timed out");
1617 jsr166 1.81 // Thread.yield();
1618     // }
1619     // }
1620    
1621 jsr166 1.45 public static class NPETask implements Callable<String> {
1622 dl 1.10 public String call() { throw new NullPointerException(); }
1623     }
1624    
1625 jsr166 1.45 public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1626     protected void realRun() {
1627 dl 1.6 try {
1628 dl 1.76 delay(SMALL_DELAY_MS);
1629 jsr166 1.44 } catch (InterruptedException ok) {}
1630 dl 1.6 }
1631     }
1632    
1633 jsr166 1.63 public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1634     return new CheckedRunnable() {
1635     protected void realRun() {
1636     try {
1637 dl 1.76 delay(timeoutMillis);
1638 jsr166 1.63 } catch (InterruptedException ok) {}
1639     }};
1640     }
1641    
1642 dl 1.5 /**
1643     * For use as ThreadFactory in constructors
1644     */
1645 jsr166 1.45 public static class SimpleThreadFactory implements ThreadFactory {
1646 jsr166 1.33 public Thread newThread(Runnable r) {
1647 dl 1.5 return new Thread(r);
1648 jsr166 1.27 }
1649 dl 1.5 }
1650    
1651 jsr166 1.61 public interface TrackedRunnable extends Runnable {
1652     boolean isDone();
1653     }
1654    
1655 jsr166 1.45 public static class TrackedNoOpRunnable implements Runnable {
1656     public volatile boolean done = false;
1657 dl 1.6 public void run() {
1658     done = true;
1659 dl 1.5 }
1660     }
1661    
1662 jsr166 1.53 /**
1663     * Analog of CheckedRunnable for RecursiveAction
1664     */
1665     public abstract class CheckedRecursiveAction extends RecursiveAction {
1666     protected abstract void realCompute() throws Throwable;
1667    
1668 jsr166 1.108 @Override protected final void compute() {
1669 jsr166 1.53 try {
1670     realCompute();
1671 jsr166 1.128 } catch (Throwable fail) {
1672     threadUnexpectedException(fail);
1673 jsr166 1.53 }
1674     }
1675     }
1676    
1677     /**
1678     * Analog of CheckedCallable for RecursiveTask
1679     */
1680     public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1681     protected abstract T realCompute() throws Throwable;
1682    
1683 jsr166 1.108 @Override protected final T compute() {
1684 jsr166 1.53 try {
1685     return realCompute();
1686 jsr166 1.128 } catch (Throwable fail) {
1687     threadUnexpectedException(fail);
1688 jsr166 1.53 return null;
1689     }
1690     }
1691     }
1692 dl 1.5
1693     /**
1694     * For use as RejectedExecutionHandler in constructors
1695     */
1696 jsr166 1.45 public static class NoOpREHandler implements RejectedExecutionHandler {
1697 jsr166 1.35 public void rejectedExecution(Runnable r,
1698     ThreadPoolExecutor executor) {}
1699 dl 1.5 }
1700 jsr166 1.27
1701 jsr166 1.60 /**
1702 jsr166 1.86 * A CyclicBarrier that uses timed await and fails with
1703 jsr166 1.239 * AssertionErrors instead of throwing checked exceptions.
1704 jsr166 1.60 */
1705 jsr166 1.202 public static class CheckedBarrier extends CyclicBarrier {
1706 jsr166 1.60 public CheckedBarrier(int parties) { super(parties); }
1707    
1708     public int await() {
1709     try {
1710 jsr166 1.86 return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1711 jsr166 1.128 } catch (TimeoutException timedOut) {
1712 jsr166 1.239 throw new AssertionError("timed out");
1713 jsr166 1.128 } catch (Exception fail) {
1714 jsr166 1.239 throw new AssertionError("Unexpected exception: " + fail, fail);
1715 jsr166 1.60 }
1716     }
1717     }
1718    
1719 jsr166 1.81 void checkEmpty(BlockingQueue q) {
1720 jsr166 1.72 try {
1721     assertTrue(q.isEmpty());
1722     assertEquals(0, q.size());
1723     assertNull(q.peek());
1724     assertNull(q.poll());
1725 jsr166 1.232 assertNull(q.poll(randomExpiredTimeout(), randomTimeUnit()));
1726 jsr166 1.72 assertEquals(q.toString(), "[]");
1727     assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1728     assertFalse(q.iterator().hasNext());
1729     try {
1730     q.element();
1731     shouldThrow();
1732     } catch (NoSuchElementException success) {}
1733     try {
1734     q.iterator().next();
1735     shouldThrow();
1736     } catch (NoSuchElementException success) {}
1737     try {
1738     q.remove();
1739     shouldThrow();
1740     } catch (NoSuchElementException success) {}
1741 jsr166 1.128 } catch (InterruptedException fail) { threadUnexpectedException(fail); }
1742 jsr166 1.72 }
1743    
1744 jsr166 1.91 void assertSerialEquals(Object x, Object y) {
1745     assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1746     }
1747    
1748     void assertNotSerialEquals(Object x, Object y) {
1749     assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1750     }
1751    
1752     byte[] serialBytes(Object o) {
1753 jsr166 1.79 try {
1754     ByteArrayOutputStream bos = new ByteArrayOutputStream();
1755     ObjectOutputStream oos = new ObjectOutputStream(bos);
1756     oos.writeObject(o);
1757     oos.flush();
1758     oos.close();
1759 jsr166 1.91 return bos.toByteArray();
1760 jsr166 1.128 } catch (Throwable fail) {
1761     threadUnexpectedException(fail);
1762 jsr166 1.91 return new byte[0];
1763     }
1764     }
1765    
1766 jsr166 1.210 void assertImmutable(final Object o) {
1767 jsr166 1.208 if (o instanceof Collection) {
1768     assertThrows(
1769     UnsupportedOperationException.class,
1770     new Runnable() { public void run() {
1771     ((Collection) o).add(null);}});
1772     }
1773     }
1774 jsr166 1.209
1775 jsr166 1.91 @SuppressWarnings("unchecked")
1776     <T> T serialClone(T o) {
1777     try {
1778 jsr166 1.87 ObjectInputStream ois = new ObjectInputStream
1779 jsr166 1.91 (new ByteArrayInputStream(serialBytes(o)));
1780 jsr166 1.87 T clone = (T) ois.readObject();
1781 jsr166 1.208 if (o == clone) assertImmutable(o);
1782 jsr166 1.87 assertSame(o.getClass(), clone.getClass());
1783     return clone;
1784 jsr166 1.128 } catch (Throwable fail) {
1785     threadUnexpectedException(fail);
1786 jsr166 1.79 return null;
1787     }
1788     }
1789 jsr166 1.106
1790 jsr166 1.208 /**
1791 jsr166 1.211 * A version of serialClone that leaves error handling (for
1792     * e.g. NotSerializableException) up to the caller.
1793     */
1794     @SuppressWarnings("unchecked")
1795     <T> T serialClonePossiblyFailing(T o)
1796     throws ReflectiveOperationException, java.io.IOException {
1797     ByteArrayOutputStream bos = new ByteArrayOutputStream();
1798     ObjectOutputStream oos = new ObjectOutputStream(bos);
1799     oos.writeObject(o);
1800     oos.flush();
1801     oos.close();
1802     ObjectInputStream ois = new ObjectInputStream
1803     (new ByteArrayInputStream(bos.toByteArray()));
1804     T clone = (T) ois.readObject();
1805     if (o == clone) assertImmutable(o);
1806     assertSame(o.getClass(), clone.getClass());
1807     return clone;
1808     }
1809    
1810     /**
1811 jsr166 1.208 * If o implements Cloneable and has a public clone method,
1812     * returns a clone of o, else null.
1813     */
1814     @SuppressWarnings("unchecked")
1815     <T> T cloneableClone(T o) {
1816     if (!(o instanceof Cloneable)) return null;
1817     final T clone;
1818     try {
1819     clone = (T) o.getClass().getMethod("clone").invoke(o);
1820     } catch (NoSuchMethodException ok) {
1821     return null;
1822     } catch (ReflectiveOperationException unexpected) {
1823     throw new Error(unexpected);
1824     }
1825     assertNotSame(o, clone); // not 100% guaranteed by spec
1826     assertSame(o.getClass(), clone.getClass());
1827     return clone;
1828     }
1829    
1830 jsr166 1.106 public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1831     Runnable... throwingActions) {
1832     for (Runnable throwingAction : throwingActions) {
1833     boolean threw = false;
1834     try { throwingAction.run(); }
1835     catch (Throwable t) {
1836     threw = true;
1837 jsr166 1.239 if (!expectedExceptionClass.isInstance(t))
1838     throw new AssertionError(
1839     "Expected " + expectedExceptionClass.getName() +
1840     ", got " + t.getClass().getName(),
1841     t);
1842 jsr166 1.106 }
1843     if (!threw)
1844     shouldThrow(expectedExceptionClass.getName());
1845     }
1846     }
1847 jsr166 1.126
1848     public void assertIteratorExhausted(Iterator<?> it) {
1849     try {
1850     it.next();
1851     shouldThrow();
1852     } catch (NoSuchElementException success) {}
1853     assertFalse(it.hasNext());
1854 jsr166 1.127 }
1855 jsr166 1.191
1856     public <T> Callable<T> callableThrowing(final Exception ex) {
1857     return new Callable<T>() { public T call() throws Exception { throw ex; }};
1858     }
1859    
1860     public Runnable runnableThrowing(final RuntimeException ex) {
1861     return new Runnable() { public void run() { throw ex; }};
1862     }
1863 jsr166 1.193
1864     /** A reusable thread pool to be shared by tests. */
1865     static final ExecutorService cachedThreadPool =
1866     new ThreadPoolExecutor(0, Integer.MAX_VALUE,
1867     1000L, MILLISECONDS,
1868     new SynchronousQueue<Runnable>());
1869    
1870 jsr166 1.234 static <T> void shuffle(T[] array) {
1871     Collections.shuffle(Arrays.asList(array), ThreadLocalRandom.current());
1872     }
1873    
1874 jsr166 1.236 /**
1875     * Returns the same String as would be returned by {@link
1876     * Object#toString}, whether or not the given object's class
1877     * overrides toString().
1878     *
1879     * @see System#identityHashCode
1880     */
1881     static String identityString(Object x) {
1882     return x.getClass().getName()
1883     + "@" + Integer.toHexString(System.identityHashCode(x));
1884     }
1885    
1886 jsr166 1.234 // --- Shared assertions for Executor tests ---
1887    
1888 jsr166 1.233 /**
1889     * Returns maximum number of tasks that can be submitted to given
1890     * pool (with bounded queue) before saturation (when submission
1891     * throws RejectedExecutionException).
1892     */
1893     static final int saturatedSize(ThreadPoolExecutor pool) {
1894     BlockingQueue<Runnable> q = pool.getQueue();
1895     return pool.getMaximumPoolSize() + q.size() + q.remainingCapacity();
1896     }
1897    
1898 jsr166 1.234 @SuppressWarnings("FutureReturnValueIgnored")
1899     void assertNullTaskSubmissionThrowsNullPointerException(Executor e) {
1900     try {
1901     e.execute((Runnable) null);
1902     shouldThrow();
1903     } catch (NullPointerException success) {}
1904    
1905     if (! (e instanceof ExecutorService)) return;
1906     ExecutorService es = (ExecutorService) e;
1907     try {
1908     es.submit((Runnable) null);
1909     shouldThrow();
1910     } catch (NullPointerException success) {}
1911     try {
1912     es.submit((Runnable) null, Boolean.TRUE);
1913     shouldThrow();
1914     } catch (NullPointerException success) {}
1915     try {
1916     es.submit((Callable) null);
1917     shouldThrow();
1918     } catch (NullPointerException success) {}
1919    
1920     if (! (e instanceof ScheduledExecutorService)) return;
1921     ScheduledExecutorService ses = (ScheduledExecutorService) e;
1922     try {
1923     ses.schedule((Runnable) null,
1924     randomTimeout(), randomTimeUnit());
1925     shouldThrow();
1926     } catch (NullPointerException success) {}
1927     try {
1928     ses.schedule((Callable) null,
1929     randomTimeout(), randomTimeUnit());
1930     shouldThrow();
1931     } catch (NullPointerException success) {}
1932     try {
1933     ses.scheduleAtFixedRate((Runnable) null,
1934     randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
1935     shouldThrow();
1936     } catch (NullPointerException success) {}
1937     try {
1938     ses.scheduleWithFixedDelay((Runnable) null,
1939     randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
1940     shouldThrow();
1941     } catch (NullPointerException success) {}
1942     }
1943    
1944     void setRejectedExecutionHandler(
1945     ThreadPoolExecutor p, RejectedExecutionHandler handler) {
1946     p.setRejectedExecutionHandler(handler);
1947     assertSame(handler, p.getRejectedExecutionHandler());
1948     }
1949    
1950     void assertTaskSubmissionsAreRejected(ThreadPoolExecutor p) {
1951     final RejectedExecutionHandler savedHandler = p.getRejectedExecutionHandler();
1952     final long savedTaskCount = p.getTaskCount();
1953     final long savedCompletedTaskCount = p.getCompletedTaskCount();
1954     final int savedQueueSize = p.getQueue().size();
1955     final boolean stock = (p.getClass().getClassLoader() == null);
1956    
1957     Runnable r = () -> {};
1958     Callable<Boolean> c = () -> Boolean.TRUE;
1959    
1960     class Recorder implements RejectedExecutionHandler {
1961     public volatile Runnable r = null;
1962     public volatile ThreadPoolExecutor p = null;
1963     public void reset() { r = null; p = null; }
1964     public void rejectedExecution(Runnable r, ThreadPoolExecutor p) {
1965     assertNull(this.r);
1966     assertNull(this.p);
1967     this.r = r;
1968     this.p = p;
1969     }
1970     }
1971    
1972     // check custom handler is invoked exactly once per task
1973     Recorder recorder = new Recorder();
1974     setRejectedExecutionHandler(p, recorder);
1975     for (int i = 2; i--> 0; ) {
1976     recorder.reset();
1977     p.execute(r);
1978     if (stock && p.getClass() == ThreadPoolExecutor.class)
1979     assertSame(r, recorder.r);
1980     assertSame(p, recorder.p);
1981    
1982     recorder.reset();
1983     assertFalse(p.submit(r).isDone());
1984     if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
1985     assertSame(p, recorder.p);
1986    
1987     recorder.reset();
1988     assertFalse(p.submit(r, Boolean.TRUE).isDone());
1989     if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
1990     assertSame(p, recorder.p);
1991    
1992     recorder.reset();
1993     assertFalse(p.submit(c).isDone());
1994     if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
1995     assertSame(p, recorder.p);
1996    
1997     if (p instanceof ScheduledExecutorService) {
1998     ScheduledExecutorService s = (ScheduledExecutorService) p;
1999     ScheduledFuture<?> future;
2000    
2001     recorder.reset();
2002     future = s.schedule(r, randomTimeout(), randomTimeUnit());
2003     assertFalse(future.isDone());
2004     if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2005     assertSame(p, recorder.p);
2006    
2007     recorder.reset();
2008     future = s.schedule(c, randomTimeout(), randomTimeUnit());
2009     assertFalse(future.isDone());
2010     if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2011     assertSame(p, recorder.p);
2012    
2013     recorder.reset();
2014     future = s.scheduleAtFixedRate(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2015     assertFalse(future.isDone());
2016     if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2017     assertSame(p, recorder.p);
2018    
2019     recorder.reset();
2020     future = s.scheduleWithFixedDelay(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2021     assertFalse(future.isDone());
2022     if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2023     assertSame(p, recorder.p);
2024     }
2025     }
2026    
2027     // Checking our custom handler above should be sufficient, but
2028     // we add some integration tests of standard handlers.
2029     final AtomicReference<Thread> thread = new AtomicReference<>();
2030     final Runnable setThread = () -> thread.set(Thread.currentThread());
2031    
2032     setRejectedExecutionHandler(p, new ThreadPoolExecutor.AbortPolicy());
2033     try {
2034     p.execute(setThread);
2035     shouldThrow();
2036     } catch (RejectedExecutionException success) {}
2037     assertNull(thread.get());
2038    
2039     setRejectedExecutionHandler(p, new ThreadPoolExecutor.DiscardPolicy());
2040     p.execute(setThread);
2041     assertNull(thread.get());
2042    
2043     setRejectedExecutionHandler(p, new ThreadPoolExecutor.CallerRunsPolicy());
2044     p.execute(setThread);
2045     if (p.isShutdown())
2046     assertNull(thread.get());
2047     else
2048     assertSame(Thread.currentThread(), thread.get());
2049    
2050     setRejectedExecutionHandler(p, savedHandler);
2051    
2052     // check that pool was not perturbed by handlers
2053     assertEquals(savedTaskCount, p.getTaskCount());
2054     assertEquals(savedCompletedTaskCount, p.getCompletedTaskCount());
2055     assertEquals(savedQueueSize, p.getQueue().size());
2056 jsr166 1.200 }
2057 jsr166 1.243
2058     void assertCollectionsEquals(Collection<?> x, Collection<?> y) {
2059     assertEquals(x, y);
2060     assertEquals(y, x);
2061     assertEquals(x.isEmpty(), y.isEmpty());
2062     assertEquals(x.size(), y.size());
2063     if (x instanceof List) {
2064     assertEquals(x.toString(), y.toString());
2065     }
2066     if (x instanceof List || x instanceof Set) {
2067     assertEquals(x.hashCode(), y.hashCode());
2068     }
2069     if (x instanceof List || x instanceof Deque) {
2070     assertTrue(Arrays.equals(x.toArray(), y.toArray()));
2071     assertTrue(Arrays.equals(x.toArray(new Object[0]),
2072     y.toArray(new Object[0])));
2073     }
2074     }
2075    
2076     /**
2077     * A weaker form of assertCollectionsEquals which does not insist
2078     * that the two collections satisfy Object#equals(Object), since
2079     * they may use identity semantics as Deques do.
2080     */
2081     void assertCollectionsEquivalent(Collection<?> x, Collection<?> y) {
2082     if (x instanceof List || x instanceof Set)
2083     assertCollectionsEquals(x, y);
2084     else {
2085     assertEquals(x.isEmpty(), y.isEmpty());
2086     assertEquals(x.size(), y.size());
2087     assertEquals(new HashSet(x), new HashSet(y));
2088     if (x instanceof Deque) {
2089     assertTrue(Arrays.equals(x.toArray(), y.toArray()));
2090     assertTrue(Arrays.equals(x.toArray(new Object[0]),
2091     y.toArray(new Object[0])));
2092     }
2093     }
2094     }
2095 dl 1.1 }