ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.194
Committed: Mon May 23 18:42:17 2016 UTC (7 years, 11 months ago) by jsr166
Branch: MAIN
Changes since 1.193: +1 -0 lines
Log Message:
Test common pool parallelism of 0 with jtreg

File Contents

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