ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.233
Committed: Sat Jul 15 23:15:21 2017 UTC (6 years, 9 months ago) by jsr166
Branch: MAIN
Changes since 1.232: +10 -0 lines
Log Message:
improve tests of saturated pools

File Contents

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