ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.214
Committed: Fri Dec 9 07:26:04 2016 UTC (7 years, 4 months ago) by jsr166
Branch: MAIN
Changes since 1.213: +12 -2 lines
Log Message:
add another @run to test common pool parallelism of 1 and java.util.secureRandomSeed=true

File Contents

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