ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.137
Committed: Fri Sep 4 18:27:33 2015 UTC (8 years, 8 months ago) by jsr166
Branch: MAIN
Changes since 1.136: +5 -4 lines
Log Message:
even more fiddling with atLeastJava9 and atLeastJava10

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