ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.199
Committed: Sat Aug 6 16:24:05 2016 UTC (7 years, 8 months ago) by jsr166
Branch: MAIN
Changes since 1.198: +3 -1 lines
Log Message:
waitForThreadToEnterWaitState: only call nanoTime if necessary

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