ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.217
Committed: Tue Jan 24 22:57:02 2017 UTC (7 years, 3 months ago) by jsr166
Branch: MAIN
Changes since 1.216: +3 -0 lines
Log Message:
add security manager tests

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