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