ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.136
Committed: Fri Sep 4 18:16:28 2015 UTC (8 years, 8 months ago) by jsr166
Branch: MAIN
Changes since 1.135: +8 -1 lines
Log Message:
Fix (broken) atLeastJava9, and boldly try to add 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     // As of 2015-09, java9 still uses 52.0 class file version
286     return JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?(9|[0-9][0-9])$");
287     }
288     // public static boolean atLeastJava9() { return JAVA_CLASS_VERSION >= 53.0; }
289     public static boolean atLeastJava10() {
290     return JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?[0-9][0-9]$");
291     }
292 jsr166 1.97
293 dl 1.6 /**
294 jsr166 1.60 * Collects all JSR166 unit tests as one suite.
295 jsr166 1.27 */
296 jsr166 1.41 public static Test suite() {
297 jsr166 1.98 // Java7+ test classes
298 jsr166 1.97 TestSuite suite = newTestSuite(
299 jsr166 1.60 ForkJoinPoolTest.suite(),
300     ForkJoinTaskTest.suite(),
301     RecursiveActionTest.suite(),
302     RecursiveTaskTest.suite(),
303     LinkedTransferQueueTest.suite(),
304     PhaserTest.suite(),
305     ThreadLocalRandomTest.suite(),
306     AbstractExecutorServiceTest.suite(),
307     AbstractQueueTest.suite(),
308     AbstractQueuedSynchronizerTest.suite(),
309     AbstractQueuedLongSynchronizerTest.suite(),
310     ArrayBlockingQueueTest.suite(),
311     ArrayDequeTest.suite(),
312     AtomicBooleanTest.suite(),
313     AtomicIntegerArrayTest.suite(),
314     AtomicIntegerFieldUpdaterTest.suite(),
315     AtomicIntegerTest.suite(),
316     AtomicLongArrayTest.suite(),
317     AtomicLongFieldUpdaterTest.suite(),
318     AtomicLongTest.suite(),
319     AtomicMarkableReferenceTest.suite(),
320     AtomicReferenceArrayTest.suite(),
321     AtomicReferenceFieldUpdaterTest.suite(),
322     AtomicReferenceTest.suite(),
323     AtomicStampedReferenceTest.suite(),
324     ConcurrentHashMapTest.suite(),
325     ConcurrentLinkedDequeTest.suite(),
326     ConcurrentLinkedQueueTest.suite(),
327     ConcurrentSkipListMapTest.suite(),
328     ConcurrentSkipListSubMapTest.suite(),
329     ConcurrentSkipListSetTest.suite(),
330     ConcurrentSkipListSubSetTest.suite(),
331     CopyOnWriteArrayListTest.suite(),
332     CopyOnWriteArraySetTest.suite(),
333     CountDownLatchTest.suite(),
334     CyclicBarrierTest.suite(),
335     DelayQueueTest.suite(),
336     EntryTest.suite(),
337     ExchangerTest.suite(),
338     ExecutorsTest.suite(),
339     ExecutorCompletionServiceTest.suite(),
340     FutureTaskTest.suite(),
341     LinkedBlockingDequeTest.suite(),
342     LinkedBlockingQueueTest.suite(),
343     LinkedListTest.suite(),
344     LockSupportTest.suite(),
345     PriorityBlockingQueueTest.suite(),
346     PriorityQueueTest.suite(),
347     ReentrantLockTest.suite(),
348     ReentrantReadWriteLockTest.suite(),
349     ScheduledExecutorTest.suite(),
350     ScheduledExecutorSubclassTest.suite(),
351     SemaphoreTest.suite(),
352     SynchronousQueueTest.suite(),
353     SystemTest.suite(),
354     ThreadLocalTest.suite(),
355     ThreadPoolExecutorTest.suite(),
356     ThreadPoolExecutorSubclassTest.suite(),
357     ThreadTest.suite(),
358     TimeUnitTest.suite(),
359     TreeMapTest.suite(),
360     TreeSetTest.suite(),
361     TreeSubMapTest.suite(),
362     TreeSubSetTest.suite());
363 jsr166 1.98
364     // Java8+ test classes
365     if (atLeastJava8()) {
366     String[] java8TestClassNames = {
367 dl 1.113 "Atomic8Test",
368 dl 1.104 "CompletableFutureTest",
369 dl 1.105 "ConcurrentHashMap8Test",
370 dl 1.104 "CountedCompleterTest",
371     "DoubleAccumulatorTest",
372 dl 1.103 "DoubleAdderTest",
373 jsr166 1.102 "ForkJoinPool8Test",
374 dl 1.111 "ForkJoinTask8Test",
375 dl 1.104 "LongAccumulatorTest",
376     "LongAdderTest",
377 jsr166 1.110 "SplittableRandomTest",
378 jsr166 1.98 "StampedLockTest",
379 jsr166 1.112 "ThreadLocalRandom8Test",
380 jsr166 1.98 };
381     addNamedTestClasses(suite, java8TestClassNames);
382 jsr166 1.97 }
383 jsr166 1.98
384 jsr166 1.115 // Java9+ test classes
385     if (atLeastJava9()) {
386     String[] java9TestClassNames = {
387     "ThreadPoolExecutor9Test",
388     };
389     addNamedTestClasses(suite, java9TestClassNames);
390     }
391    
392 jsr166 1.97 return suite;
393 dl 1.6 }
394    
395 jsr166 1.134 /** Returns list of junit-style test method names in given class. */
396     public static ArrayList<String> testMethodNames(Class<?> testClass) {
397     Method[] methods = testClass.getDeclaredMethods();
398     ArrayList<String> names = new ArrayList<String>(methods.length);
399     for (Method method : methods) {
400     if (method.getName().startsWith("test")
401     && Modifier.isPublic(method.getModifiers())
402     // method.getParameterCount() requires jdk8+
403     && method.getParameterTypes().length == 0) {
404     names.add(method.getName());
405     }
406     }
407     return names;
408     }
409    
410     /**
411     * Returns junit-style testSuite for the given test class, but
412     * parameterized by passing extra data to each test.
413     */
414     public static <ExtraData> Test parameterizedTestSuite
415     (Class<? extends JSR166TestCase> testClass,
416     Class<ExtraData> dataClass,
417     ExtraData data) {
418     try {
419     TestSuite suite = new TestSuite();
420     Constructor c =
421     testClass.getDeclaredConstructor(dataClass, String.class);
422     for (String methodName : testMethodNames(testClass))
423     suite.addTest((Test) c.newInstance(data, methodName));
424     return suite;
425     } catch (Exception e) {
426     throw new Error(e);
427     }
428     }
429    
430     /**
431     * Returns junit-style testSuite for the jdk8 extension of the
432     * given test class, but parameterized by passing extra data to
433     * each test. Uses reflection to allow compilation in jdk7.
434     */
435     public static <ExtraData> Test jdk8ParameterizedTestSuite
436     (Class<? extends JSR166TestCase> testClass,
437     Class<ExtraData> dataClass,
438     ExtraData data) {
439     if (atLeastJava8()) {
440     String name = testClass.getName();
441     String name8 = name.replaceAll("Test$", "8Test");
442     if (name.equals(name8)) throw new Error(name);
443     try {
444     return (Test)
445     Class.forName(name8)
446     .getMethod("testSuite", new Class[] { dataClass })
447     .invoke(null, data);
448     } catch (Exception e) {
449     throw new Error(e);
450     }
451     } else {
452     return new TestSuite();
453     }
454    
455     }
456    
457 jsr166 1.109 // Delays for timing-dependent tests, in milliseconds.
458 dl 1.1
459 dl 1.2 public static long SHORT_DELAY_MS;
460     public static long SMALL_DELAY_MS;
461     public static long MEDIUM_DELAY_MS;
462     public static long LONG_DELAY_MS;
463    
464     /**
465 jsr166 1.27 * Returns the shortest timed delay. This could
466 dl 1.15 * be reimplemented to use for example a Property.
467 jsr166 1.27 */
468 dl 1.2 protected long getShortDelay() {
469 dl 1.21 return 50;
470 dl 1.2 }
471    
472     /**
473 jsr166 1.27 * Sets delays as multiples of SHORT_DELAY.
474 dl 1.2 */
475 jsr166 1.43 protected void setDelays() {
476 dl 1.2 SHORT_DELAY_MS = getShortDelay();
477 jsr166 1.53 SMALL_DELAY_MS = SHORT_DELAY_MS * 5;
478 dl 1.2 MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
479 jsr166 1.71 LONG_DELAY_MS = SHORT_DELAY_MS * 200;
480 dl 1.2 }
481    
482 dl 1.1 /**
483 jsr166 1.81 * Returns a timeout in milliseconds to be used in tests that
484     * verify that operations block or time out.
485     */
486     long timeoutMillis() {
487     return SHORT_DELAY_MS / 4;
488     }
489    
490     /**
491 jsr166 1.135 * Returns a new Date instance representing a time at least
492     * delayMillis milliseconds in the future.
493 jsr166 1.81 */
494     Date delayedDate(long delayMillis) {
495 jsr166 1.135 // Add 1 because currentTimeMillis is known to round into the past.
496     return new Date(System.currentTimeMillis() + delayMillis + 1);
497 jsr166 1.81 }
498    
499     /**
500 jsr166 1.53 * The first exception encountered if any threadAssertXXX method fails.
501 dl 1.1 */
502 jsr166 1.53 private final AtomicReference<Throwable> threadFailure
503     = new AtomicReference<Throwable>(null);
504 dl 1.1
505     /**
506 jsr166 1.53 * Records an exception so that it can be rethrown later in the test
507     * harness thread, triggering a test case failure. Only the first
508     * failure is recorded; subsequent calls to this method from within
509     * the same test have no effect.
510 dl 1.1 */
511 jsr166 1.53 public void threadRecordFailure(Throwable t) {
512     threadFailure.compareAndSet(null, t);
513     }
514    
515 jsr166 1.27 public void setUp() {
516 dl 1.2 setDelays();
517 dl 1.1 }
518    
519     /**
520 jsr166 1.85 * Extra checks that get done for all test cases.
521     *
522 jsr166 1.53 * Triggers test case failure if any thread assertions have failed,
523     * by rethrowing, in the test harness thread, any exception recorded
524     * earlier by threadRecordFailure.
525 jsr166 1.85 *
526     * Triggers test case failure if interrupt status is set in the main thread.
527 jsr166 1.53 */
528     public void tearDown() throws Exception {
529 jsr166 1.70 Throwable t = threadFailure.getAndSet(null);
530 jsr166 1.53 if (t != null) {
531     if (t instanceof Error)
532     throw (Error) t;
533     else if (t instanceof RuntimeException)
534     throw (RuntimeException) t;
535     else if (t instanceof Exception)
536     throw (Exception) t;
537 jsr166 1.57 else {
538     AssertionFailedError afe =
539     new AssertionFailedError(t.toString());
540     afe.initCause(t);
541     throw afe;
542     }
543 jsr166 1.53 }
544 jsr166 1.85
545     if (Thread.interrupted())
546     throw new AssertionFailedError("interrupt status set in main thread");
547 jsr166 1.100
548     checkForkJoinPoolThreadLeaks();
549 dl 1.1 }
550    
551 dl 1.5 /**
552 jsr166 1.125 * Finds missing try { ... } finally { joinPool(e); }
553 jsr166 1.100 */
554     void checkForkJoinPoolThreadLeaks() throws InterruptedException {
555     Thread[] survivors = new Thread[5];
556     int count = Thread.enumerate(survivors);
557     for (int i = 0; i < count; i++) {
558     Thread thread = survivors[i];
559     String name = thread.getName();
560     if (name.startsWith("ForkJoinPool-")) {
561     // give thread some time to terminate
562     thread.join(LONG_DELAY_MS);
563     if (!thread.isAlive()) continue;
564     throw new AssertionFailedError
565     (String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n",
566     toString(), name));
567     }
568     }
569     }
570 jsr166 1.101
571 jsr166 1.100 /**
572 jsr166 1.53 * Just like fail(reason), but additionally recording (using
573 jsr166 1.57 * threadRecordFailure) any AssertionFailedError thrown, so that
574     * the current testcase will fail.
575 jsr166 1.27 */
576 dl 1.1 public void threadFail(String reason) {
577 jsr166 1.53 try {
578     fail(reason);
579 jsr166 1.57 } catch (AssertionFailedError t) {
580 jsr166 1.53 threadRecordFailure(t);
581     fail(reason);
582     }
583 dl 1.1 }
584    
585 dl 1.5 /**
586 jsr166 1.53 * Just like assertTrue(b), but additionally recording (using
587 jsr166 1.57 * threadRecordFailure) any AssertionFailedError thrown, so that
588     * the current testcase will fail.
589 jsr166 1.27 */
590 dl 1.1 public void threadAssertTrue(boolean b) {
591 jsr166 1.53 try {
592 dl 1.1 assertTrue(b);
593 jsr166 1.57 } catch (AssertionFailedError t) {
594 jsr166 1.53 threadRecordFailure(t);
595     throw t;
596 dl 1.1 }
597     }
598 dl 1.5
599     /**
600 jsr166 1.53 * Just like assertFalse(b), but additionally recording (using
601 jsr166 1.57 * threadRecordFailure) any AssertionFailedError thrown, so that
602     * the current testcase will fail.
603 jsr166 1.27 */
604 dl 1.1 public void threadAssertFalse(boolean b) {
605 jsr166 1.53 try {
606 dl 1.1 assertFalse(b);
607 jsr166 1.57 } catch (AssertionFailedError t) {
608 jsr166 1.53 threadRecordFailure(t);
609     throw t;
610 dl 1.1 }
611     }
612 dl 1.5
613     /**
614 jsr166 1.53 * Just like assertNull(x), but additionally recording (using
615 jsr166 1.57 * threadRecordFailure) any AssertionFailedError thrown, so that
616     * the current testcase will fail.
617 jsr166 1.27 */
618 dl 1.1 public void threadAssertNull(Object x) {
619 jsr166 1.53 try {
620 dl 1.1 assertNull(x);
621 jsr166 1.57 } catch (AssertionFailedError t) {
622 jsr166 1.53 threadRecordFailure(t);
623     throw t;
624 dl 1.1 }
625     }
626 dl 1.5
627     /**
628 jsr166 1.53 * Just like assertEquals(x, y), but additionally recording (using
629 jsr166 1.57 * threadRecordFailure) any AssertionFailedError thrown, so that
630     * the current testcase will fail.
631 jsr166 1.27 */
632 dl 1.1 public void threadAssertEquals(long x, long y) {
633 jsr166 1.53 try {
634 dl 1.1 assertEquals(x, y);
635 jsr166 1.57 } catch (AssertionFailedError t) {
636 jsr166 1.53 threadRecordFailure(t);
637     throw t;
638 dl 1.1 }
639     }
640 dl 1.5
641     /**
642 jsr166 1.53 * Just like assertEquals(x, y), but additionally recording (using
643 jsr166 1.57 * threadRecordFailure) any AssertionFailedError thrown, so that
644     * the current testcase will fail.
645 jsr166 1.27 */
646 dl 1.1 public void threadAssertEquals(Object x, Object y) {
647 jsr166 1.53 try {
648 dl 1.1 assertEquals(x, y);
649 jsr166 1.129 } catch (AssertionFailedError fail) {
650     threadRecordFailure(fail);
651     throw fail;
652     } catch (Throwable fail) {
653     threadUnexpectedException(fail);
654 dl 1.1 }
655     }
656    
657 dl 1.5 /**
658 jsr166 1.53 * Just like assertSame(x, y), but additionally recording (using
659 jsr166 1.57 * threadRecordFailure) any AssertionFailedError thrown, so that
660     * the current testcase will fail.
661 jsr166 1.52 */
662     public void threadAssertSame(Object x, Object y) {
663 jsr166 1.53 try {
664 jsr166 1.52 assertSame(x, y);
665 jsr166 1.129 } catch (AssertionFailedError fail) {
666     threadRecordFailure(fail);
667     throw fail;
668 jsr166 1.52 }
669     }
670    
671     /**
672 jsr166 1.53 * Calls threadFail with message "should throw exception".
673 jsr166 1.33 */
674 dl 1.3 public void threadShouldThrow() {
675 jsr166 1.53 threadFail("should throw exception");
676 dl 1.3 }
677    
678 dl 1.5 /**
679 jsr166 1.53 * Calls threadFail with message "should throw" + exceptionName.
680 jsr166 1.40 */
681     public void threadShouldThrow(String exceptionName) {
682 jsr166 1.53 threadFail("should throw " + exceptionName);
683 dl 1.3 }
684    
685 dl 1.31 /**
686 jsr166 1.57 * Records the given exception using {@link #threadRecordFailure},
687     * then rethrows the exception, wrapping it in an
688     * AssertionFailedError if necessary.
689 dl 1.31 */
690 jsr166 1.53 public void threadUnexpectedException(Throwable t) {
691     threadRecordFailure(t);
692     t.printStackTrace();
693     if (t instanceof RuntimeException)
694     throw (RuntimeException) t;
695     else if (t instanceof Error)
696     throw (Error) t;
697     else {
698 jsr166 1.57 AssertionFailedError afe =
699     new AssertionFailedError("unexpected exception: " + t);
700 jsr166 1.82 afe.initCause(t);
701 jsr166 1.57 throw afe;
702 jsr166 1.55 }
703 dl 1.31 }
704 dl 1.3
705 dl 1.1 /**
706 jsr166 1.81 * Delays, via Thread.sleep, for the given millisecond delay, but
707 dl 1.76 * if the sleep is shorter than specified, may re-sleep or yield
708     * until time elapses.
709     */
710 jsr166 1.81 static void delay(long millis) throws InterruptedException {
711 dl 1.76 long startTime = System.nanoTime();
712 jsr166 1.80 long ns = millis * 1000 * 1000;
713 dl 1.76 for (;;) {
714 jsr166 1.80 if (millis > 0L)
715     Thread.sleep(millis);
716 dl 1.76 else // too short to sleep
717     Thread.yield();
718     long d = ns - (System.nanoTime() - startTime);
719     if (d > 0L)
720 jsr166 1.80 millis = d / (1000 * 1000);
721 dl 1.76 else
722     break;
723     }
724     }
725    
726     /**
727 jsr166 1.53 * Waits out termination of a thread pool or fails doing so.
728 dl 1.1 */
729 jsr166 1.81 void joinPool(ExecutorService exec) {
730 dl 1.1 try {
731     exec.shutdown();
732 jsr166 1.121 if (!exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS))
733     fail("ExecutorService " + exec +
734     " did not terminate in a timely manner");
735 jsr166 1.33 } catch (SecurityException ok) {
736 dl 1.22 // Allowed in case test doesn't have privs
737 jsr166 1.128 } catch (InterruptedException fail) {
738 jsr166 1.44 fail("Unexpected InterruptedException");
739 dl 1.1 }
740     }
741    
742 jsr166 1.78 /**
743 jsr166 1.95 * A debugging tool to print all stack traces, as jstack does.
744     */
745 jsr166 1.96 static void printAllStackTraces() {
746     for (ThreadInfo info :
747     ManagementFactory.getThreadMXBean()
748     .dumpAllThreads(true, true))
749     System.err.print(info);
750 jsr166 1.95 }
751    
752     /**
753 jsr166 1.81 * Checks that thread does not terminate within the default
754     * millisecond delay of {@code timeoutMillis()}.
755     */
756     void assertThreadStaysAlive(Thread thread) {
757     assertThreadStaysAlive(thread, timeoutMillis());
758     }
759    
760     /**
761 jsr166 1.80 * Checks that thread does not terminate within the given millisecond delay.
762 jsr166 1.78 */
763 jsr166 1.81 void assertThreadStaysAlive(Thread thread, long millis) {
764 jsr166 1.78 try {
765 jsr166 1.80 // No need to optimize the failing case via Thread.join.
766     delay(millis);
767 jsr166 1.78 assertTrue(thread.isAlive());
768 jsr166 1.128 } catch (InterruptedException fail) {
769 jsr166 1.78 fail("Unexpected InterruptedException");
770     }
771     }
772 dl 1.5
773     /**
774 jsr166 1.90 * Checks that the threads do not terminate within the default
775     * millisecond delay of {@code timeoutMillis()}.
776     */
777     void assertThreadsStayAlive(Thread... threads) {
778     assertThreadsStayAlive(timeoutMillis(), threads);
779     }
780    
781     /**
782     * Checks that the threads do not terminate within the given millisecond delay.
783     */
784     void assertThreadsStayAlive(long millis, Thread... threads) {
785     try {
786     // No need to optimize the failing case via Thread.join.
787     delay(millis);
788     for (Thread thread : threads)
789     assertTrue(thread.isAlive());
790 jsr166 1.128 } catch (InterruptedException fail) {
791 jsr166 1.90 fail("Unexpected InterruptedException");
792     }
793     }
794    
795     /**
796 jsr166 1.83 * Checks that future.get times out, with the default timeout of
797     * {@code timeoutMillis()}.
798     */
799     void assertFutureTimesOut(Future future) {
800     assertFutureTimesOut(future, timeoutMillis());
801     }
802    
803     /**
804     * Checks that future.get times out, with the given millisecond timeout.
805     */
806     void assertFutureTimesOut(Future future, long timeoutMillis) {
807     long startTime = System.nanoTime();
808     try {
809     future.get(timeoutMillis, MILLISECONDS);
810     shouldThrow();
811     } catch (TimeoutException success) {
812 jsr166 1.128 } catch (Exception fail) {
813     threadUnexpectedException(fail);
814 jsr166 1.83 } finally { future.cancel(true); }
815     assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
816     }
817    
818     /**
819 jsr166 1.53 * Fails with message "should throw exception".
820 jsr166 1.27 */
821 dl 1.3 public void shouldThrow() {
822     fail("Should throw exception");
823     }
824    
825 dl 1.5 /**
826 jsr166 1.53 * Fails with message "should throw " + exceptionName.
827 jsr166 1.40 */
828     public void shouldThrow(String exceptionName) {
829     fail("Should throw " + exceptionName);
830     }
831    
832     /**
833 dl 1.1 * The number of elements to place in collections, arrays, etc.
834     */
835 jsr166 1.45 public static final int SIZE = 20;
836 dl 1.1
837     // Some convenient Integer constants
838    
839 jsr166 1.47 public static final Integer zero = new Integer(0);
840     public static final Integer one = new Integer(1);
841     public static final Integer two = new Integer(2);
842     public static final Integer three = new Integer(3);
843 jsr166 1.45 public static final Integer four = new Integer(4);
844     public static final Integer five = new Integer(5);
845 jsr166 1.47 public static final Integer six = new Integer(6);
846 jsr166 1.45 public static final Integer seven = new Integer(7);
847     public static final Integer eight = new Integer(8);
848 jsr166 1.47 public static final Integer nine = new Integer(9);
849 jsr166 1.45 public static final Integer m1 = new Integer(-1);
850     public static final Integer m2 = new Integer(-2);
851     public static final Integer m3 = new Integer(-3);
852 jsr166 1.47 public static final Integer m4 = new Integer(-4);
853     public static final Integer m5 = new Integer(-5);
854     public static final Integer m6 = new Integer(-6);
855 jsr166 1.45 public static final Integer m10 = new Integer(-10);
856 dl 1.7
857     /**
858 jsr166 1.49 * Runs Runnable r with a security policy that permits precisely
859     * the specified permissions. If there is no current security
860     * manager, the runnable is run twice, both with and without a
861     * security manager. We require that any security manager permit
862     * getPolicy/setPolicy.
863     */
864     public void runWithPermissions(Runnable r, Permission... permissions) {
865     SecurityManager sm = System.getSecurityManager();
866     if (sm == null) {
867     r.run();
868 jsr166 1.93 }
869     runWithSecurityManagerWithPermissions(r, permissions);
870     }
871    
872     /**
873     * Runs Runnable r with a security policy that permits precisely
874     * the specified permissions. If there is no current security
875     * manager, a temporary one is set for the duration of the
876     * Runnable. We require that any security manager permit
877     * getPolicy/setPolicy.
878     */
879     public void runWithSecurityManagerWithPermissions(Runnable r,
880     Permission... permissions) {
881     SecurityManager sm = System.getSecurityManager();
882     if (sm == null) {
883 jsr166 1.49 Policy savedPolicy = Policy.getPolicy();
884     try {
885     Policy.setPolicy(permissivePolicy());
886     System.setSecurityManager(new SecurityManager());
887 jsr166 1.93 runWithSecurityManagerWithPermissions(r, permissions);
888 jsr166 1.49 } finally {
889     System.setSecurityManager(null);
890     Policy.setPolicy(savedPolicy);
891     }
892     } else {
893     Policy savedPolicy = Policy.getPolicy();
894     AdjustablePolicy policy = new AdjustablePolicy(permissions);
895     Policy.setPolicy(policy);
896    
897     try {
898     r.run();
899     } finally {
900     policy.addPermission(new SecurityPermission("setPolicy"));
901     Policy.setPolicy(savedPolicy);
902     }
903     }
904     }
905    
906     /**
907     * Runs a runnable without any permissions.
908     */
909     public void runWithoutPermissions(Runnable r) {
910     runWithPermissions(r);
911     }
912    
913     /**
914 dl 1.7 * A security policy where new permissions can be dynamically added
915     * or all cleared.
916     */
917 jsr166 1.45 public static class AdjustablePolicy extends java.security.Policy {
918 dl 1.7 Permissions perms = new Permissions();
919 jsr166 1.49 AdjustablePolicy(Permission... permissions) {
920     for (Permission permission : permissions)
921     perms.add(permission);
922     }
923 dl 1.7 void addPermission(Permission perm) { perms.add(perm); }
924     void clearPermissions() { perms = new Permissions(); }
925 jsr166 1.42 public PermissionCollection getPermissions(CodeSource cs) {
926     return perms;
927     }
928     public PermissionCollection getPermissions(ProtectionDomain pd) {
929     return perms;
930     }
931     public boolean implies(ProtectionDomain pd, Permission p) {
932     return perms.implies(p);
933     }
934     public void refresh() {}
935 jsr166 1.93 public String toString() {
936     List<Permission> ps = new ArrayList<Permission>();
937     for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
938     ps.add(e.nextElement());
939     return "AdjustablePolicy with permissions " + ps;
940     }
941 dl 1.7 }
942 dl 1.1
943 jsr166 1.38 /**
944 jsr166 1.49 * Returns a policy containing all the permissions we ever need.
945     */
946     public static Policy permissivePolicy() {
947     return new AdjustablePolicy
948     // Permissions j.u.c. needs directly
949     (new RuntimePermission("modifyThread"),
950     new RuntimePermission("getClassLoader"),
951     new RuntimePermission("setContextClassLoader"),
952     // Permissions needed to change permissions!
953     new SecurityPermission("getPolicy"),
954     new SecurityPermission("setPolicy"),
955     new RuntimePermission("setSecurityManager"),
956     // Permissions needed by the junit test harness
957     new RuntimePermission("accessDeclaredMembers"),
958     new PropertyPermission("*", "read"),
959     new java.io.FilePermission("<<ALL FILES>>", "read"));
960     }
961    
962     /**
963 jsr166 1.60 * Sleeps until the given time has elapsed.
964     * Throws AssertionFailedError if interrupted.
965     */
966     void sleep(long millis) {
967     try {
968 dl 1.76 delay(millis);
969 jsr166 1.128 } catch (InterruptedException fail) {
970 jsr166 1.60 AssertionFailedError afe =
971     new AssertionFailedError("Unexpected InterruptedException");
972 jsr166 1.128 afe.initCause(fail);
973 jsr166 1.60 throw afe;
974     }
975     }
976    
977     /**
978 jsr166 1.88 * Spin-waits up to the specified number of milliseconds for the given
979 jsr166 1.65 * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
980     */
981     void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
982 jsr166 1.88 long startTime = System.nanoTime();
983 jsr166 1.65 for (;;) {
984     Thread.State s = thread.getState();
985     if (s == Thread.State.BLOCKED ||
986     s == Thread.State.WAITING ||
987 jsr166 1.67 s == Thread.State.TIMED_WAITING)
988 jsr166 1.65 return;
989 jsr166 1.67 else if (s == Thread.State.TERMINATED)
990     fail("Unexpected thread termination");
991 jsr166 1.88 else if (millisElapsedSince(startTime) > timeoutMillis) {
992 jsr166 1.67 threadAssertTrue(thread.isAlive());
993     return;
994     }
995 jsr166 1.65 Thread.yield();
996     }
997     }
998    
999     /**
1000 jsr166 1.75 * Waits up to LONG_DELAY_MS for the given thread to enter a wait
1001     * state: BLOCKED, WAITING, or TIMED_WAITING.
1002     */
1003     void waitForThreadToEnterWaitState(Thread thread) {
1004     waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
1005     }
1006    
1007     /**
1008 jsr166 1.66 * Returns the number of milliseconds since time given by
1009     * startNanoTime, which must have been previously returned from a
1010 jsr166 1.124 * call to {@link System#nanoTime()}.
1011 jsr166 1.66 */
1012 jsr166 1.117 static long millisElapsedSince(long startNanoTime) {
1013 jsr166 1.66 return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
1014     }
1015 jsr166 1.68
1016 jsr166 1.120 // void assertTerminatesPromptly(long timeoutMillis, Runnable r) {
1017     // long startTime = System.nanoTime();
1018     // try {
1019     // r.run();
1020     // } catch (Throwable fail) { threadUnexpectedException(fail); }
1021     // if (millisElapsedSince(startTime) > timeoutMillis/2)
1022     // throw new AssertionFailedError("did not return promptly");
1023     // }
1024    
1025     // void assertTerminatesPromptly(Runnable r) {
1026     // assertTerminatesPromptly(LONG_DELAY_MS/2, r);
1027     // }
1028    
1029     /**
1030     * Checks that timed f.get() returns the expected value, and does not
1031     * wait for the timeout to elapse before returning.
1032     */
1033     <T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) {
1034     long startTime = System.nanoTime();
1035     try {
1036     assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
1037     } catch (Throwable fail) { threadUnexpectedException(fail); }
1038     if (millisElapsedSince(startTime) > timeoutMillis/2)
1039     throw new AssertionFailedError("timed get did not return promptly");
1040     }
1041    
1042     <T> void checkTimedGet(Future<T> f, T expectedValue) {
1043     checkTimedGet(f, expectedValue, LONG_DELAY_MS);
1044     }
1045    
1046 jsr166 1.66 /**
1047 jsr166 1.58 * Returns a new started daemon Thread running the given runnable.
1048 jsr166 1.38 */
1049     Thread newStartedThread(Runnable runnable) {
1050     Thread t = new Thread(runnable);
1051 jsr166 1.58 t.setDaemon(true);
1052 jsr166 1.38 t.start();
1053     return t;
1054     }
1055 dl 1.1
1056 jsr166 1.59 /**
1057     * Waits for the specified time (in milliseconds) for the thread
1058     * to terminate (using {@link Thread#join(long)}), else interrupts
1059     * the thread (in the hope that it may terminate later) and fails.
1060     */
1061     void awaitTermination(Thread t, long timeoutMillis) {
1062     try {
1063     t.join(timeoutMillis);
1064 jsr166 1.128 } catch (InterruptedException fail) {
1065     threadUnexpectedException(fail);
1066 jsr166 1.59 } finally {
1067 jsr166 1.83 if (t.getState() != Thread.State.TERMINATED) {
1068 jsr166 1.59 t.interrupt();
1069     fail("Test timed out");
1070     }
1071     }
1072     }
1073    
1074 jsr166 1.75 /**
1075     * Waits for LONG_DELAY_MS milliseconds for the thread to
1076     * terminate (using {@link Thread#join(long)}), else interrupts
1077     * the thread (in the hope that it may terminate later) and fails.
1078     */
1079     void awaitTermination(Thread t) {
1080     awaitTermination(t, LONG_DELAY_MS);
1081     }
1082    
1083 dl 1.1 // Some convenient Runnable classes
1084    
1085 jsr166 1.45 public abstract class CheckedRunnable implements Runnable {
1086     protected abstract void realRun() throws Throwable;
1087 jsr166 1.35
1088     public final void run() {
1089     try {
1090     realRun();
1091 jsr166 1.128 } catch (Throwable fail) {
1092     threadUnexpectedException(fail);
1093 jsr166 1.35 }
1094     }
1095     }
1096    
1097 jsr166 1.45 public abstract class RunnableShouldThrow implements Runnable {
1098     protected abstract void realRun() throws Throwable;
1099 jsr166 1.40
1100     final Class<?> exceptionClass;
1101    
1102     <T extends Throwable> RunnableShouldThrow(Class<T> exceptionClass) {
1103     this.exceptionClass = exceptionClass;
1104     }
1105    
1106     public final void run() {
1107     try {
1108     realRun();
1109     threadShouldThrow(exceptionClass.getSimpleName());
1110     } catch (Throwable t) {
1111     if (! exceptionClass.isInstance(t))
1112     threadUnexpectedException(t);
1113     }
1114     }
1115     }
1116    
1117 jsr166 1.45 public abstract class ThreadShouldThrow extends Thread {
1118     protected abstract void realRun() throws Throwable;
1119 jsr166 1.40
1120     final Class<?> exceptionClass;
1121    
1122     <T extends Throwable> ThreadShouldThrow(Class<T> exceptionClass) {
1123     this.exceptionClass = exceptionClass;
1124     }
1125    
1126     public final void run() {
1127     try {
1128     realRun();
1129     threadShouldThrow(exceptionClass.getSimpleName());
1130     } catch (Throwable t) {
1131     if (! exceptionClass.isInstance(t))
1132     threadUnexpectedException(t);
1133     }
1134     }
1135     }
1136    
1137 jsr166 1.45 public abstract class CheckedInterruptedRunnable implements Runnable {
1138     protected abstract void realRun() throws Throwable;
1139 jsr166 1.35
1140     public final void run() {
1141     try {
1142     realRun();
1143 jsr166 1.40 threadShouldThrow("InterruptedException");
1144 jsr166 1.35 } catch (InterruptedException success) {
1145 jsr166 1.81 threadAssertFalse(Thread.interrupted());
1146 jsr166 1.128 } catch (Throwable fail) {
1147     threadUnexpectedException(fail);
1148 jsr166 1.35 }
1149     }
1150     }
1151    
1152 jsr166 1.45 public abstract class CheckedCallable<T> implements Callable<T> {
1153     protected abstract T realCall() throws Throwable;
1154 jsr166 1.35
1155     public final T call() {
1156     try {
1157     return realCall();
1158 jsr166 1.128 } catch (Throwable fail) {
1159     threadUnexpectedException(fail);
1160 jsr166 1.53 return null;
1161 jsr166 1.35 }
1162 jsr166 1.40 }
1163     }
1164    
1165 jsr166 1.53 public abstract class CheckedInterruptedCallable<T>
1166     implements Callable<T> {
1167 jsr166 1.45 protected abstract T realCall() throws Throwable;
1168 jsr166 1.40
1169     public final T call() {
1170     try {
1171     T result = realCall();
1172     threadShouldThrow("InterruptedException");
1173     return result;
1174     } catch (InterruptedException success) {
1175 jsr166 1.81 threadAssertFalse(Thread.interrupted());
1176 jsr166 1.128 } catch (Throwable fail) {
1177     threadUnexpectedException(fail);
1178 jsr166 1.40 }
1179     return null;
1180 jsr166 1.35 }
1181     }
1182    
1183 jsr166 1.45 public static class NoOpRunnable implements Runnable {
1184 dl 1.1 public void run() {}
1185     }
1186    
1187 jsr166 1.45 public static class NoOpCallable implements Callable {
1188 dl 1.1 public Object call() { return Boolean.TRUE; }
1189 dl 1.10 }
1190    
1191 jsr166 1.45 public static final String TEST_STRING = "a test string";
1192 dl 1.10
1193 jsr166 1.45 public static class StringTask implements Callable<String> {
1194 dl 1.10 public String call() { return TEST_STRING; }
1195     }
1196    
1197 jsr166 1.48 public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
1198     return new CheckedCallable<String>() {
1199 jsr166 1.64 protected String realCall() {
1200 jsr166 1.48 try {
1201     latch.await();
1202     } catch (InterruptedException quittingTime) {}
1203     return TEST_STRING;
1204     }};
1205     }
1206    
1207 jsr166 1.73 public Runnable awaiter(final CountDownLatch latch) {
1208     return new CheckedRunnable() {
1209     public void realRun() throws InterruptedException {
1210 jsr166 1.79 await(latch);
1211 jsr166 1.73 }};
1212     }
1213    
1214 jsr166 1.79 public void await(CountDownLatch latch) {
1215     try {
1216     assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1217 jsr166 1.128 } catch (Throwable fail) {
1218     threadUnexpectedException(fail);
1219 jsr166 1.79 }
1220     }
1221    
1222 jsr166 1.89 public void await(Semaphore semaphore) {
1223     try {
1224     assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1225 jsr166 1.128 } catch (Throwable fail) {
1226     threadUnexpectedException(fail);
1227 jsr166 1.89 }
1228     }
1229    
1230 jsr166 1.81 // /**
1231     // * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1232     // */
1233     // public void await(AtomicBoolean flag) {
1234     // await(flag, LONG_DELAY_MS);
1235     // }
1236    
1237     // /**
1238     // * Spin-waits up to the specified timeout until flag becomes true.
1239     // */
1240     // public void await(AtomicBoolean flag, long timeoutMillis) {
1241     // long startTime = System.nanoTime();
1242     // while (!flag.get()) {
1243     // if (millisElapsedSince(startTime) > timeoutMillis)
1244     // throw new AssertionFailedError("timed out");
1245     // Thread.yield();
1246     // }
1247     // }
1248    
1249 jsr166 1.45 public static class NPETask implements Callable<String> {
1250 dl 1.10 public String call() { throw new NullPointerException(); }
1251     }
1252    
1253 jsr166 1.45 public static class CallableOne implements Callable<Integer> {
1254 dl 1.10 public Integer call() { return one; }
1255 dl 1.1 }
1256    
1257 jsr166 1.45 public class ShortRunnable extends CheckedRunnable {
1258     protected void realRun() throws Throwable {
1259 dl 1.76 delay(SHORT_DELAY_MS);
1260 dl 1.1 }
1261     }
1262    
1263 jsr166 1.45 public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1264     protected void realRun() throws InterruptedException {
1265 dl 1.76 delay(SHORT_DELAY_MS);
1266 dl 1.1 }
1267     }
1268    
1269 jsr166 1.45 public class SmallRunnable extends CheckedRunnable {
1270     protected void realRun() throws Throwable {
1271 dl 1.76 delay(SMALL_DELAY_MS);
1272 dl 1.1 }
1273     }
1274    
1275 jsr166 1.45 public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1276     protected void realRun() {
1277 dl 1.6 try {
1278 dl 1.76 delay(SMALL_DELAY_MS);
1279 jsr166 1.44 } catch (InterruptedException ok) {}
1280 dl 1.6 }
1281     }
1282    
1283 jsr166 1.45 public class SmallCallable extends CheckedCallable {
1284     protected Object realCall() throws InterruptedException {
1285 dl 1.76 delay(SMALL_DELAY_MS);
1286 dl 1.1 return Boolean.TRUE;
1287     }
1288     }
1289    
1290 jsr166 1.45 public class MediumRunnable extends CheckedRunnable {
1291     protected void realRun() throws Throwable {
1292 dl 1.76 delay(MEDIUM_DELAY_MS);
1293 dl 1.1 }
1294     }
1295    
1296 jsr166 1.45 public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1297     protected void realRun() throws InterruptedException {
1298 dl 1.76 delay(MEDIUM_DELAY_MS);
1299 dl 1.1 }
1300     }
1301    
1302 jsr166 1.63 public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1303     return new CheckedRunnable() {
1304     protected void realRun() {
1305     try {
1306 dl 1.76 delay(timeoutMillis);
1307 jsr166 1.63 } catch (InterruptedException ok) {}
1308     }};
1309     }
1310    
1311 jsr166 1.45 public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1312     protected void realRun() {
1313 dl 1.1 try {
1314 dl 1.76 delay(MEDIUM_DELAY_MS);
1315 jsr166 1.44 } catch (InterruptedException ok) {}
1316 dl 1.1 }
1317     }
1318 dl 1.5
1319 jsr166 1.45 public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1320     protected void realRun() {
1321 dl 1.12 try {
1322 dl 1.76 delay(LONG_DELAY_MS);
1323 jsr166 1.44 } catch (InterruptedException ok) {}
1324 dl 1.12 }
1325     }
1326    
1327 dl 1.5 /**
1328     * For use as ThreadFactory in constructors
1329     */
1330 jsr166 1.45 public static class SimpleThreadFactory implements ThreadFactory {
1331 jsr166 1.33 public Thread newThread(Runnable r) {
1332 dl 1.5 return new Thread(r);
1333 jsr166 1.27 }
1334 dl 1.5 }
1335    
1336 jsr166 1.61 public interface TrackedRunnable extends Runnable {
1337     boolean isDone();
1338     }
1339    
1340     public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
1341     return new TrackedRunnable() {
1342     private volatile boolean done = false;
1343     public boolean isDone() { return done; }
1344     public void run() {
1345     try {
1346 dl 1.76 delay(timeoutMillis);
1347 jsr166 1.61 done = true;
1348     } catch (InterruptedException ok) {}
1349     }
1350     };
1351     }
1352    
1353 jsr166 1.45 public static class TrackedShortRunnable implements Runnable {
1354     public volatile boolean done = false;
1355 dl 1.5 public void run() {
1356     try {
1357 dl 1.76 delay(SHORT_DELAY_MS);
1358 jsr166 1.61 done = true;
1359     } catch (InterruptedException ok) {}
1360     }
1361     }
1362    
1363     public static class TrackedSmallRunnable implements Runnable {
1364     public volatile boolean done = false;
1365     public void run() {
1366     try {
1367 dl 1.76 delay(SMALL_DELAY_MS);
1368 dl 1.5 done = true;
1369 jsr166 1.44 } catch (InterruptedException ok) {}
1370 dl 1.6 }
1371     }
1372    
1373 jsr166 1.45 public static class TrackedMediumRunnable implements Runnable {
1374     public volatile boolean done = false;
1375 dl 1.6 public void run() {
1376     try {
1377 dl 1.76 delay(MEDIUM_DELAY_MS);
1378 dl 1.6 done = true;
1379 jsr166 1.44 } catch (InterruptedException ok) {}
1380 dl 1.6 }
1381     }
1382    
1383 jsr166 1.45 public static class TrackedLongRunnable implements Runnable {
1384     public volatile boolean done = false;
1385 dl 1.6 public void run() {
1386     try {
1387 dl 1.76 delay(LONG_DELAY_MS);
1388 dl 1.6 done = true;
1389 jsr166 1.44 } catch (InterruptedException ok) {}
1390 dl 1.6 }
1391     }
1392    
1393 jsr166 1.45 public static class TrackedNoOpRunnable implements Runnable {
1394     public volatile boolean done = false;
1395 dl 1.6 public void run() {
1396     done = true;
1397 dl 1.5 }
1398     }
1399    
1400 jsr166 1.45 public static class TrackedCallable implements Callable {
1401     public volatile boolean done = false;
1402 dl 1.5 public Object call() {
1403     try {
1404 dl 1.76 delay(SMALL_DELAY_MS);
1405 dl 1.5 done = true;
1406 jsr166 1.44 } catch (InterruptedException ok) {}
1407 dl 1.5 return Boolean.TRUE;
1408     }
1409     }
1410 dl 1.14
1411 jsr166 1.53 /**
1412     * Analog of CheckedRunnable for RecursiveAction
1413     */
1414     public abstract class CheckedRecursiveAction extends RecursiveAction {
1415     protected abstract void realCompute() throws Throwable;
1416    
1417 jsr166 1.108 @Override protected final void compute() {
1418 jsr166 1.53 try {
1419     realCompute();
1420 jsr166 1.128 } catch (Throwable fail) {
1421     threadUnexpectedException(fail);
1422 jsr166 1.53 }
1423     }
1424     }
1425    
1426     /**
1427     * Analog of CheckedCallable for RecursiveTask
1428     */
1429     public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1430     protected abstract T realCompute() throws Throwable;
1431    
1432 jsr166 1.108 @Override protected final T compute() {
1433 jsr166 1.53 try {
1434     return realCompute();
1435 jsr166 1.128 } catch (Throwable fail) {
1436     threadUnexpectedException(fail);
1437 jsr166 1.53 return null;
1438     }
1439     }
1440     }
1441 dl 1.5
1442     /**
1443     * For use as RejectedExecutionHandler in constructors
1444     */
1445 jsr166 1.45 public static class NoOpREHandler implements RejectedExecutionHandler {
1446 jsr166 1.35 public void rejectedExecution(Runnable r,
1447     ThreadPoolExecutor executor) {}
1448 dl 1.5 }
1449 jsr166 1.27
1450 jsr166 1.60 /**
1451 jsr166 1.86 * A CyclicBarrier that uses timed await and fails with
1452     * AssertionFailedErrors instead of throwing checked exceptions.
1453 jsr166 1.60 */
1454     public class CheckedBarrier extends CyclicBarrier {
1455     public CheckedBarrier(int parties) { super(parties); }
1456    
1457     public int await() {
1458     try {
1459 jsr166 1.86 return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1460 jsr166 1.128 } catch (TimeoutException timedOut) {
1461 jsr166 1.86 throw new AssertionFailedError("timed out");
1462 jsr166 1.128 } catch (Exception fail) {
1463 jsr166 1.60 AssertionFailedError afe =
1464 jsr166 1.128 new AssertionFailedError("Unexpected exception: " + fail);
1465     afe.initCause(fail);
1466 jsr166 1.60 throw afe;
1467     }
1468     }
1469     }
1470    
1471 jsr166 1.81 void checkEmpty(BlockingQueue q) {
1472 jsr166 1.72 try {
1473     assertTrue(q.isEmpty());
1474     assertEquals(0, q.size());
1475     assertNull(q.peek());
1476     assertNull(q.poll());
1477     assertNull(q.poll(0, MILLISECONDS));
1478     assertEquals(q.toString(), "[]");
1479     assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1480     assertFalse(q.iterator().hasNext());
1481     try {
1482     q.element();
1483     shouldThrow();
1484     } catch (NoSuchElementException success) {}
1485     try {
1486     q.iterator().next();
1487     shouldThrow();
1488     } catch (NoSuchElementException success) {}
1489     try {
1490     q.remove();
1491     shouldThrow();
1492     } catch (NoSuchElementException success) {}
1493 jsr166 1.128 } catch (InterruptedException fail) { threadUnexpectedException(fail); }
1494 jsr166 1.72 }
1495    
1496 jsr166 1.91 void assertSerialEquals(Object x, Object y) {
1497     assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1498     }
1499    
1500     void assertNotSerialEquals(Object x, Object y) {
1501     assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1502     }
1503    
1504     byte[] serialBytes(Object o) {
1505 jsr166 1.79 try {
1506     ByteArrayOutputStream bos = new ByteArrayOutputStream();
1507     ObjectOutputStream oos = new ObjectOutputStream(bos);
1508     oos.writeObject(o);
1509     oos.flush();
1510     oos.close();
1511 jsr166 1.91 return bos.toByteArray();
1512 jsr166 1.128 } catch (Throwable fail) {
1513     threadUnexpectedException(fail);
1514 jsr166 1.91 return new byte[0];
1515     }
1516     }
1517    
1518     @SuppressWarnings("unchecked")
1519     <T> T serialClone(T o) {
1520     try {
1521 jsr166 1.87 ObjectInputStream ois = new ObjectInputStream
1522 jsr166 1.91 (new ByteArrayInputStream(serialBytes(o)));
1523 jsr166 1.87 T clone = (T) ois.readObject();
1524     assertSame(o.getClass(), clone.getClass());
1525     return clone;
1526 jsr166 1.128 } catch (Throwable fail) {
1527     threadUnexpectedException(fail);
1528 jsr166 1.79 return null;
1529     }
1530     }
1531 jsr166 1.106
1532     public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1533     Runnable... throwingActions) {
1534     for (Runnable throwingAction : throwingActions) {
1535     boolean threw = false;
1536     try { throwingAction.run(); }
1537     catch (Throwable t) {
1538     threw = true;
1539     if (!expectedExceptionClass.isInstance(t)) {
1540     AssertionFailedError afe =
1541     new AssertionFailedError
1542     ("Expected " + expectedExceptionClass.getName() +
1543     ", got " + t.getClass().getName());
1544     afe.initCause(t);
1545     threadUnexpectedException(afe);
1546     }
1547     }
1548     if (!threw)
1549     shouldThrow(expectedExceptionClass.getName());
1550     }
1551     }
1552 jsr166 1.126
1553     public void assertIteratorExhausted(Iterator<?> it) {
1554     try {
1555     it.next();
1556     shouldThrow();
1557     } catch (NoSuchElementException success) {}
1558     assertFalse(it.hasNext());
1559 jsr166 1.127 }
1560 dl 1.1 }