ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.212
Committed: Fri Dec 9 04:24:07 2016 UTC (7 years, 4 months ago) by jsr166
Branch: MAIN
Changes since 1.211: +2 -1 lines
Log Message:
sync @modules ... :open from upstream for module refresh

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