ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.196
Committed: Fri Jun 17 19:00:48 2016 UTC (7 years, 10 months ago) by jsr166
Branch: MAIN
Changes since 1.195: +7 -0 lines
Log Message:
split jdk9 Atomic tests into separate *9Test.java files

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.196 "AtomicBoolean9Test",
525     "AtomicInteger9Test",
526     "AtomicIntegerArray9Test",
527     "AtomicLong9Test",
528     "AtomicLongArray9Test",
529     "AtomicReference9Test",
530     "AtomicReferenceArray9Test",
531 jsr166 1.192 "ExecutorCompletionService9Test",
532 jsr166 1.115 };
533     addNamedTestClasses(suite, java9TestClassNames);
534     }
535    
536 jsr166 1.97 return suite;
537 dl 1.6 }
538    
539 jsr166 1.134 /** Returns list of junit-style test method names in given class. */
540     public static ArrayList<String> testMethodNames(Class<?> testClass) {
541     Method[] methods = testClass.getDeclaredMethods();
542     ArrayList<String> names = new ArrayList<String>(methods.length);
543     for (Method method : methods) {
544     if (method.getName().startsWith("test")
545     && Modifier.isPublic(method.getModifiers())
546     // method.getParameterCount() requires jdk8+
547     && method.getParameterTypes().length == 0) {
548     names.add(method.getName());
549     }
550     }
551     return names;
552     }
553    
554     /**
555     * Returns junit-style testSuite for the given test class, but
556     * parameterized by passing extra data to each test.
557     */
558     public static <ExtraData> Test parameterizedTestSuite
559     (Class<? extends JSR166TestCase> testClass,
560     Class<ExtraData> dataClass,
561     ExtraData data) {
562     try {
563     TestSuite suite = new TestSuite();
564     Constructor c =
565     testClass.getDeclaredConstructor(dataClass, String.class);
566     for (String methodName : testMethodNames(testClass))
567     suite.addTest((Test) c.newInstance(data, methodName));
568     return suite;
569     } catch (Exception e) {
570     throw new Error(e);
571     }
572     }
573    
574     /**
575     * Returns junit-style testSuite for the jdk8 extension of the
576     * given test class, but parameterized by passing extra data to
577     * each test. Uses reflection to allow compilation in jdk7.
578     */
579     public static <ExtraData> Test jdk8ParameterizedTestSuite
580     (Class<? extends JSR166TestCase> testClass,
581     Class<ExtraData> dataClass,
582     ExtraData data) {
583     if (atLeastJava8()) {
584     String name = testClass.getName();
585     String name8 = name.replaceAll("Test$", "8Test");
586     if (name.equals(name8)) throw new Error(name);
587     try {
588     return (Test)
589     Class.forName(name8)
590     .getMethod("testSuite", new Class[] { dataClass })
591     .invoke(null, data);
592     } catch (Exception e) {
593     throw new Error(e);
594     }
595     } else {
596     return new TestSuite();
597     }
598     }
599    
600 jsr166 1.109 // Delays for timing-dependent tests, in milliseconds.
601 dl 1.1
602 dl 1.2 public static long SHORT_DELAY_MS;
603     public static long SMALL_DELAY_MS;
604     public static long MEDIUM_DELAY_MS;
605     public static long LONG_DELAY_MS;
606    
607     /**
608 jsr166 1.181 * Returns the shortest timed delay. This can be scaled up for
609 jsr166 1.185 * slow machines using the jsr166.delay.factor system property,
610 jsr166 1.187 * or via jtreg's -timeoutFactor: flag.
611 jsr166 1.185 * http://openjdk.java.net/jtreg/command-help.html
612 jsr166 1.27 */
613 dl 1.2 protected long getShortDelay() {
614 jsr166 1.189 return (long) (50 * delayFactor);
615 dl 1.2 }
616    
617     /**
618 jsr166 1.27 * Sets delays as multiples of SHORT_DELAY.
619 dl 1.2 */
620 jsr166 1.43 protected void setDelays() {
621 dl 1.2 SHORT_DELAY_MS = getShortDelay();
622 jsr166 1.53 SMALL_DELAY_MS = SHORT_DELAY_MS * 5;
623 dl 1.2 MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
624 jsr166 1.71 LONG_DELAY_MS = SHORT_DELAY_MS * 200;
625 dl 1.2 }
626    
627 dl 1.1 /**
628 jsr166 1.81 * Returns a timeout in milliseconds to be used in tests that
629     * verify that operations block or time out.
630     */
631     long timeoutMillis() {
632     return SHORT_DELAY_MS / 4;
633     }
634    
635     /**
636 jsr166 1.135 * Returns a new Date instance representing a time at least
637     * delayMillis milliseconds in the future.
638 jsr166 1.81 */
639     Date delayedDate(long delayMillis) {
640 jsr166 1.135 // Add 1 because currentTimeMillis is known to round into the past.
641     return new Date(System.currentTimeMillis() + delayMillis + 1);
642 jsr166 1.81 }
643    
644     /**
645 jsr166 1.53 * The first exception encountered if any threadAssertXXX method fails.
646 dl 1.1 */
647 jsr166 1.53 private final AtomicReference<Throwable> threadFailure
648     = new AtomicReference<Throwable>(null);
649 dl 1.1
650     /**
651 jsr166 1.53 * Records an exception so that it can be rethrown later in the test
652     * harness thread, triggering a test case failure. Only the first
653     * failure is recorded; subsequent calls to this method from within
654     * the same test have no effect.
655 dl 1.1 */
656 jsr166 1.53 public void threadRecordFailure(Throwable t) {
657 jsr166 1.158 System.err.println(t);
658 jsr166 1.156 dumpTestThreads();
659 jsr166 1.53 threadFailure.compareAndSet(null, t);
660     }
661    
662 jsr166 1.27 public void setUp() {
663 dl 1.2 setDelays();
664 dl 1.1 }
665    
666 jsr166 1.146 void tearDownFail(String format, Object... args) {
667     String msg = toString() + ": " + String.format(format, args);
668     System.err.println(msg);
669 jsr166 1.156 dumpTestThreads();
670 jsr166 1.146 throw new AssertionFailedError(msg);
671     }
672    
673 dl 1.1 /**
674 jsr166 1.85 * Extra checks that get done for all test cases.
675     *
676 jsr166 1.53 * Triggers test case failure if any thread assertions have failed,
677     * by rethrowing, in the test harness thread, any exception recorded
678     * earlier by threadRecordFailure.
679 jsr166 1.85 *
680     * Triggers test case failure if interrupt status is set in the main thread.
681 jsr166 1.53 */
682     public void tearDown() throws Exception {
683 jsr166 1.70 Throwable t = threadFailure.getAndSet(null);
684 jsr166 1.53 if (t != null) {
685     if (t instanceof Error)
686     throw (Error) t;
687     else if (t instanceof RuntimeException)
688     throw (RuntimeException) t;
689     else if (t instanceof Exception)
690     throw (Exception) t;
691 jsr166 1.57 else {
692     AssertionFailedError afe =
693     new AssertionFailedError(t.toString());
694     afe.initCause(t);
695     throw afe;
696     }
697 jsr166 1.53 }
698 jsr166 1.85
699     if (Thread.interrupted())
700 jsr166 1.146 tearDownFail("interrupt status set in main thread");
701 jsr166 1.100
702     checkForkJoinPoolThreadLeaks();
703 dl 1.1 }
704    
705 dl 1.5 /**
706 jsr166 1.164 * Finds missing PoolCleaners
707 jsr166 1.100 */
708     void checkForkJoinPoolThreadLeaks() throws InterruptedException {
709 jsr166 1.146 Thread[] survivors = new Thread[7];
710 jsr166 1.100 int count = Thread.enumerate(survivors);
711     for (int i = 0; i < count; i++) {
712     Thread thread = survivors[i];
713     String name = thread.getName();
714     if (name.startsWith("ForkJoinPool-")) {
715     // give thread some time to terminate
716     thread.join(LONG_DELAY_MS);
717 jsr166 1.146 if (thread.isAlive())
718     tearDownFail("Found leaked ForkJoinPool thread thread=%s",
719     thread);
720 jsr166 1.100 }
721     }
722 jsr166 1.146
723     if (!ForkJoinPool.commonPool()
724     .awaitQuiescence(LONG_DELAY_MS, MILLISECONDS))
725     tearDownFail("ForkJoin common pool thread stuck");
726 jsr166 1.100 }
727 jsr166 1.101
728 jsr166 1.100 /**
729 jsr166 1.53 * Just like fail(reason), but additionally recording (using
730 jsr166 1.57 * threadRecordFailure) any AssertionFailedError thrown, so that
731     * the current testcase will fail.
732 jsr166 1.27 */
733 dl 1.1 public void threadFail(String reason) {
734 jsr166 1.53 try {
735     fail(reason);
736 jsr166 1.57 } catch (AssertionFailedError t) {
737 jsr166 1.53 threadRecordFailure(t);
738 jsr166 1.152 throw t;
739 jsr166 1.53 }
740 dl 1.1 }
741    
742 dl 1.5 /**
743 jsr166 1.53 * Just like assertTrue(b), but additionally recording (using
744 jsr166 1.57 * threadRecordFailure) any AssertionFailedError thrown, so that
745     * the current testcase will fail.
746 jsr166 1.27 */
747 dl 1.1 public void threadAssertTrue(boolean b) {
748 jsr166 1.53 try {
749 dl 1.1 assertTrue(b);
750 jsr166 1.57 } catch (AssertionFailedError t) {
751 jsr166 1.53 threadRecordFailure(t);
752     throw t;
753 dl 1.1 }
754     }
755 dl 1.5
756     /**
757 jsr166 1.53 * Just like assertFalse(b), but additionally recording (using
758 jsr166 1.57 * threadRecordFailure) any AssertionFailedError thrown, so that
759     * the current testcase will fail.
760 jsr166 1.27 */
761 dl 1.1 public void threadAssertFalse(boolean b) {
762 jsr166 1.53 try {
763 dl 1.1 assertFalse(b);
764 jsr166 1.57 } catch (AssertionFailedError t) {
765 jsr166 1.53 threadRecordFailure(t);
766     throw t;
767 dl 1.1 }
768     }
769 dl 1.5
770     /**
771 jsr166 1.53 * Just like assertNull(x), but additionally recording (using
772 jsr166 1.57 * threadRecordFailure) any AssertionFailedError thrown, so that
773     * the current testcase will fail.
774 jsr166 1.27 */
775 dl 1.1 public void threadAssertNull(Object x) {
776 jsr166 1.53 try {
777 dl 1.1 assertNull(x);
778 jsr166 1.57 } catch (AssertionFailedError t) {
779 jsr166 1.53 threadRecordFailure(t);
780     throw t;
781 dl 1.1 }
782     }
783 dl 1.5
784     /**
785 jsr166 1.53 * Just like assertEquals(x, y), but additionally recording (using
786 jsr166 1.57 * threadRecordFailure) any AssertionFailedError thrown, so that
787     * the current testcase will fail.
788 jsr166 1.27 */
789 dl 1.1 public void threadAssertEquals(long x, long y) {
790 jsr166 1.53 try {
791 dl 1.1 assertEquals(x, y);
792 jsr166 1.57 } catch (AssertionFailedError t) {
793 jsr166 1.53 threadRecordFailure(t);
794     throw t;
795 dl 1.1 }
796     }
797 dl 1.5
798     /**
799 jsr166 1.53 * Just like assertEquals(x, y), but additionally recording (using
800 jsr166 1.57 * threadRecordFailure) any AssertionFailedError thrown, so that
801     * the current testcase will fail.
802 jsr166 1.27 */
803 dl 1.1 public void threadAssertEquals(Object x, Object y) {
804 jsr166 1.53 try {
805 dl 1.1 assertEquals(x, y);
806 jsr166 1.129 } catch (AssertionFailedError fail) {
807     threadRecordFailure(fail);
808     throw fail;
809     } catch (Throwable fail) {
810     threadUnexpectedException(fail);
811 dl 1.1 }
812     }
813    
814 dl 1.5 /**
815 jsr166 1.53 * Just like assertSame(x, y), but additionally recording (using
816 jsr166 1.57 * threadRecordFailure) any AssertionFailedError thrown, so that
817     * the current testcase will fail.
818 jsr166 1.52 */
819     public void threadAssertSame(Object x, Object y) {
820 jsr166 1.53 try {
821 jsr166 1.52 assertSame(x, y);
822 jsr166 1.129 } catch (AssertionFailedError fail) {
823     threadRecordFailure(fail);
824     throw fail;
825 jsr166 1.52 }
826     }
827    
828     /**
829 jsr166 1.53 * Calls threadFail with message "should throw exception".
830 jsr166 1.33 */
831 dl 1.3 public void threadShouldThrow() {
832 jsr166 1.53 threadFail("should throw exception");
833 dl 1.3 }
834    
835 dl 1.5 /**
836 jsr166 1.53 * Calls threadFail with message "should throw" + exceptionName.
837 jsr166 1.40 */
838     public void threadShouldThrow(String exceptionName) {
839 jsr166 1.53 threadFail("should throw " + exceptionName);
840 dl 1.3 }
841    
842 dl 1.31 /**
843 jsr166 1.57 * Records the given exception using {@link #threadRecordFailure},
844     * then rethrows the exception, wrapping it in an
845     * AssertionFailedError if necessary.
846 dl 1.31 */
847 jsr166 1.53 public void threadUnexpectedException(Throwable t) {
848     threadRecordFailure(t);
849     t.printStackTrace();
850     if (t instanceof RuntimeException)
851     throw (RuntimeException) t;
852     else if (t instanceof Error)
853     throw (Error) t;
854     else {
855 jsr166 1.57 AssertionFailedError afe =
856     new AssertionFailedError("unexpected exception: " + t);
857 jsr166 1.82 afe.initCause(t);
858 jsr166 1.57 throw afe;
859 jsr166 1.55 }
860 dl 1.31 }
861 dl 1.3
862 dl 1.1 /**
863 jsr166 1.81 * Delays, via Thread.sleep, for the given millisecond delay, but
864 dl 1.76 * if the sleep is shorter than specified, may re-sleep or yield
865 jsr166 1.163 * until time elapses. Ensures that the given time, as measured
866     * by System.nanoTime(), has elapsed.
867 dl 1.76 */
868 jsr166 1.81 static void delay(long millis) throws InterruptedException {
869 jsr166 1.163 long nanos = millis * (1000 * 1000);
870     final long wakeupTime = System.nanoTime() + nanos;
871     do {
872 jsr166 1.80 if (millis > 0L)
873     Thread.sleep(millis);
874 dl 1.76 else // too short to sleep
875     Thread.yield();
876 jsr166 1.163 nanos = wakeupTime - System.nanoTime();
877     millis = nanos / (1000 * 1000);
878     } while (nanos >= 0L);
879 dl 1.76 }
880    
881     /**
882 jsr166 1.149 * Allows use of try-with-resources with per-test thread pools.
883     */
884 jsr166 1.160 class PoolCleaner implements AutoCloseable {
885     private final ExecutorService pool;
886     public PoolCleaner(ExecutorService pool) { this.pool = pool; }
887 jsr166 1.149 public void close() { joinPool(pool); }
888     }
889    
890 jsr166 1.166 /**
891     * An extension of PoolCleaner that has an action to release the pool.
892     */
893     class PoolCleanerWithReleaser extends PoolCleaner {
894     private final Runnable releaser;
895     public PoolCleanerWithReleaser(ExecutorService pool, Runnable releaser) {
896     super(pool);
897     this.releaser = releaser;
898     }
899     public void close() {
900     try {
901     releaser.run();
902     } finally {
903     super.close();
904     }
905     }
906     }
907    
908 jsr166 1.160 PoolCleaner cleaner(ExecutorService pool) {
909     return new PoolCleaner(pool);
910 jsr166 1.159 }
911    
912 jsr166 1.166 PoolCleaner cleaner(ExecutorService pool, Runnable releaser) {
913     return new PoolCleanerWithReleaser(pool, releaser);
914     }
915    
916     PoolCleaner cleaner(ExecutorService pool, CountDownLatch latch) {
917     return new PoolCleanerWithReleaser(pool, releaser(latch));
918     }
919    
920     Runnable releaser(final CountDownLatch latch) {
921     return new Runnable() { public void run() {
922     do { latch.countDown(); }
923     while (latch.getCount() > 0);
924     }};
925     }
926    
927 jsr166 1.185 PoolCleaner cleaner(ExecutorService pool, AtomicBoolean flag) {
928     return new PoolCleanerWithReleaser(pool, releaser(flag));
929     }
930    
931     Runnable releaser(final AtomicBoolean flag) {
932     return new Runnable() { public void run() { flag.set(true); }};
933     }
934    
935 jsr166 1.149 /**
936 jsr166 1.53 * Waits out termination of a thread pool or fails doing so.
937 dl 1.1 */
938 jsr166 1.158 void joinPool(ExecutorService pool) {
939 dl 1.1 try {
940 jsr166 1.139 pool.shutdown();
941 jsr166 1.158 if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS)) {
942     try {
943     threadFail("ExecutorService " + pool +
944     " did not terminate in a timely manner");
945     } finally {
946     // last resort, for the benefit of subsequent tests
947     pool.shutdownNow();
948 jsr166 1.167 pool.awaitTermination(MEDIUM_DELAY_MS, MILLISECONDS);
949 jsr166 1.158 }
950     }
951 jsr166 1.33 } catch (SecurityException ok) {
952 dl 1.22 // Allowed in case test doesn't have privs
953 jsr166 1.128 } catch (InterruptedException fail) {
954 jsr166 1.158 threadFail("Unexpected InterruptedException");
955 dl 1.1 }
956     }
957    
958 jsr166 1.139 /** Like Runnable, but with the freedom to throw anything */
959 jsr166 1.141 interface Action { public void run() throws Throwable; }
960 jsr166 1.139
961     /**
962 jsr166 1.141 * Runs all the given actions in parallel, failing if any fail.
963 jsr166 1.139 * Useful for running multiple variants of tests that are
964     * necessarily individually slow because they must block.
965     */
966 jsr166 1.141 void testInParallel(Action ... actions) {
967 jsr166 1.160 ExecutorService pool = Executors.newCachedThreadPool();
968     try (PoolCleaner cleaner = cleaner(pool)) {
969 jsr166 1.141 ArrayList<Future<?>> futures = new ArrayList<>(actions.length);
970     for (final Action action : actions)
971 jsr166 1.139 futures.add(pool.submit(new CheckedRunnable() {
972 jsr166 1.141 public void realRun() throws Throwable { action.run();}}));
973 jsr166 1.139 for (Future<?> future : futures)
974     try {
975     assertNull(future.get(LONG_DELAY_MS, MILLISECONDS));
976     } catch (ExecutionException ex) {
977     threadUnexpectedException(ex.getCause());
978     } catch (Exception ex) {
979     threadUnexpectedException(ex);
980     }
981     }
982     }
983    
984 jsr166 1.78 /**
985 jsr166 1.156 * A debugging tool to print stack traces of most threads, as jstack does.
986 jsr166 1.150 * Uninteresting threads are filtered out.
987 jsr166 1.95 */
988 jsr166 1.156 static void dumpTestThreads() {
989 jsr166 1.195 SecurityManager sm = System.getSecurityManager();
990     if (sm != null) {
991     try {
992     System.setSecurityManager(null);
993     } catch (SecurityException giveUp) {
994     return;
995     }
996     }
997    
998 jsr166 1.150 ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
999     System.err.println("------ stacktrace dump start ------");
1000     for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) {
1001     String name = info.getThreadName();
1002     if ("Signal Dispatcher".equals(name))
1003     continue;
1004     if ("Reference Handler".equals(name)
1005     && info.getLockName().startsWith("java.lang.ref.Reference$Lock"))
1006     continue;
1007     if ("Finalizer".equals(name)
1008     && info.getLockName().startsWith("java.lang.ref.ReferenceQueue$Lock"))
1009     continue;
1010 jsr166 1.156 if ("checkForWedgedTest".equals(name))
1011     continue;
1012 jsr166 1.96 System.err.print(info);
1013 jsr166 1.150 }
1014     System.err.println("------ stacktrace dump end ------");
1015 jsr166 1.195
1016     if (sm != null) System.setSecurityManager(sm);
1017 jsr166 1.95 }
1018    
1019     /**
1020 jsr166 1.81 * Checks that thread does not terminate within the default
1021     * millisecond delay of {@code timeoutMillis()}.
1022     */
1023     void assertThreadStaysAlive(Thread thread) {
1024     assertThreadStaysAlive(thread, timeoutMillis());
1025     }
1026    
1027     /**
1028 jsr166 1.80 * Checks that thread does not terminate within the given millisecond delay.
1029 jsr166 1.78 */
1030 jsr166 1.81 void assertThreadStaysAlive(Thread thread, long millis) {
1031 jsr166 1.78 try {
1032 jsr166 1.80 // No need to optimize the failing case via Thread.join.
1033     delay(millis);
1034 jsr166 1.78 assertTrue(thread.isAlive());
1035 jsr166 1.128 } catch (InterruptedException fail) {
1036 jsr166 1.158 threadFail("Unexpected InterruptedException");
1037 jsr166 1.78 }
1038     }
1039 dl 1.5
1040     /**
1041 jsr166 1.90 * Checks that the threads do not terminate within the default
1042     * millisecond delay of {@code timeoutMillis()}.
1043     */
1044     void assertThreadsStayAlive(Thread... threads) {
1045     assertThreadsStayAlive(timeoutMillis(), threads);
1046     }
1047    
1048     /**
1049     * Checks that the threads do not terminate within the given millisecond delay.
1050     */
1051     void assertThreadsStayAlive(long millis, Thread... threads) {
1052     try {
1053     // No need to optimize the failing case via Thread.join.
1054     delay(millis);
1055     for (Thread thread : threads)
1056     assertTrue(thread.isAlive());
1057 jsr166 1.128 } catch (InterruptedException fail) {
1058 jsr166 1.158 threadFail("Unexpected InterruptedException");
1059 jsr166 1.90 }
1060     }
1061    
1062     /**
1063 jsr166 1.83 * Checks that future.get times out, with the default timeout of
1064     * {@code timeoutMillis()}.
1065     */
1066     void assertFutureTimesOut(Future future) {
1067     assertFutureTimesOut(future, timeoutMillis());
1068     }
1069    
1070     /**
1071     * Checks that future.get times out, with the given millisecond timeout.
1072     */
1073     void assertFutureTimesOut(Future future, long timeoutMillis) {
1074     long startTime = System.nanoTime();
1075     try {
1076     future.get(timeoutMillis, MILLISECONDS);
1077     shouldThrow();
1078     } catch (TimeoutException success) {
1079 jsr166 1.128 } catch (Exception fail) {
1080     threadUnexpectedException(fail);
1081 jsr166 1.83 } finally { future.cancel(true); }
1082     assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
1083     }
1084    
1085     /**
1086 jsr166 1.53 * Fails with message "should throw exception".
1087 jsr166 1.27 */
1088 dl 1.3 public void shouldThrow() {
1089     fail("Should throw exception");
1090     }
1091    
1092 dl 1.5 /**
1093 jsr166 1.53 * Fails with message "should throw " + exceptionName.
1094 jsr166 1.40 */
1095     public void shouldThrow(String exceptionName) {
1096     fail("Should throw " + exceptionName);
1097     }
1098    
1099     /**
1100 dl 1.1 * The number of elements to place in collections, arrays, etc.
1101     */
1102 jsr166 1.45 public static final int SIZE = 20;
1103 dl 1.1
1104     // Some convenient Integer constants
1105    
1106 jsr166 1.47 public static final Integer zero = new Integer(0);
1107     public static final Integer one = new Integer(1);
1108     public static final Integer two = new Integer(2);
1109     public static final Integer three = new Integer(3);
1110 jsr166 1.45 public static final Integer four = new Integer(4);
1111     public static final Integer five = new Integer(5);
1112 jsr166 1.47 public static final Integer six = new Integer(6);
1113 jsr166 1.45 public static final Integer seven = new Integer(7);
1114     public static final Integer eight = new Integer(8);
1115 jsr166 1.47 public static final Integer nine = new Integer(9);
1116 jsr166 1.45 public static final Integer m1 = new Integer(-1);
1117     public static final Integer m2 = new Integer(-2);
1118     public static final Integer m3 = new Integer(-3);
1119 jsr166 1.47 public static final Integer m4 = new Integer(-4);
1120     public static final Integer m5 = new Integer(-5);
1121     public static final Integer m6 = new Integer(-6);
1122 jsr166 1.45 public static final Integer m10 = new Integer(-10);
1123 dl 1.7
1124     /**
1125 jsr166 1.49 * Runs Runnable r with a security policy that permits precisely
1126     * the specified permissions. If there is no current security
1127     * manager, the runnable is run twice, both with and without a
1128     * security manager. We require that any security manager permit
1129     * getPolicy/setPolicy.
1130     */
1131     public void runWithPermissions(Runnable r, Permission... permissions) {
1132     SecurityManager sm = System.getSecurityManager();
1133     if (sm == null) {
1134     r.run();
1135 jsr166 1.93 }
1136     runWithSecurityManagerWithPermissions(r, permissions);
1137     }
1138    
1139     /**
1140     * Runs Runnable r with a security policy that permits precisely
1141     * the specified permissions. If there is no current security
1142     * manager, a temporary one is set for the duration of the
1143     * Runnable. We require that any security manager permit
1144     * getPolicy/setPolicy.
1145     */
1146     public void runWithSecurityManagerWithPermissions(Runnable r,
1147     Permission... permissions) {
1148     SecurityManager sm = System.getSecurityManager();
1149     if (sm == null) {
1150 jsr166 1.49 Policy savedPolicy = Policy.getPolicy();
1151     try {
1152     Policy.setPolicy(permissivePolicy());
1153     System.setSecurityManager(new SecurityManager());
1154 jsr166 1.93 runWithSecurityManagerWithPermissions(r, permissions);
1155 jsr166 1.49 } finally {
1156     System.setSecurityManager(null);
1157     Policy.setPolicy(savedPolicy);
1158     }
1159     } else {
1160     Policy savedPolicy = Policy.getPolicy();
1161     AdjustablePolicy policy = new AdjustablePolicy(permissions);
1162     Policy.setPolicy(policy);
1163    
1164     try {
1165     r.run();
1166     } finally {
1167     policy.addPermission(new SecurityPermission("setPolicy"));
1168     Policy.setPolicy(savedPolicy);
1169     }
1170     }
1171     }
1172    
1173     /**
1174     * Runs a runnable without any permissions.
1175     */
1176     public void runWithoutPermissions(Runnable r) {
1177     runWithPermissions(r);
1178     }
1179    
1180     /**
1181 dl 1.7 * A security policy where new permissions can be dynamically added
1182     * or all cleared.
1183     */
1184 jsr166 1.45 public static class AdjustablePolicy extends java.security.Policy {
1185 dl 1.7 Permissions perms = new Permissions();
1186 jsr166 1.49 AdjustablePolicy(Permission... permissions) {
1187     for (Permission permission : permissions)
1188     perms.add(permission);
1189     }
1190 dl 1.7 void addPermission(Permission perm) { perms.add(perm); }
1191     void clearPermissions() { perms = new Permissions(); }
1192 jsr166 1.42 public PermissionCollection getPermissions(CodeSource cs) {
1193     return perms;
1194     }
1195     public PermissionCollection getPermissions(ProtectionDomain pd) {
1196     return perms;
1197     }
1198     public boolean implies(ProtectionDomain pd, Permission p) {
1199     return perms.implies(p);
1200     }
1201     public void refresh() {}
1202 jsr166 1.93 public String toString() {
1203     List<Permission> ps = new ArrayList<Permission>();
1204     for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
1205     ps.add(e.nextElement());
1206     return "AdjustablePolicy with permissions " + ps;
1207     }
1208 dl 1.7 }
1209 dl 1.1
1210 jsr166 1.38 /**
1211 jsr166 1.49 * Returns a policy containing all the permissions we ever need.
1212     */
1213     public static Policy permissivePolicy() {
1214     return new AdjustablePolicy
1215     // Permissions j.u.c. needs directly
1216     (new RuntimePermission("modifyThread"),
1217     new RuntimePermission("getClassLoader"),
1218     new RuntimePermission("setContextClassLoader"),
1219     // Permissions needed to change permissions!
1220     new SecurityPermission("getPolicy"),
1221     new SecurityPermission("setPolicy"),
1222     new RuntimePermission("setSecurityManager"),
1223     // Permissions needed by the junit test harness
1224     new RuntimePermission("accessDeclaredMembers"),
1225     new PropertyPermission("*", "read"),
1226     new java.io.FilePermission("<<ALL FILES>>", "read"));
1227     }
1228    
1229     /**
1230 jsr166 1.60 * Sleeps until the given time has elapsed.
1231     * Throws AssertionFailedError if interrupted.
1232     */
1233     void sleep(long millis) {
1234     try {
1235 dl 1.76 delay(millis);
1236 jsr166 1.128 } catch (InterruptedException fail) {
1237 jsr166 1.60 AssertionFailedError afe =
1238     new AssertionFailedError("Unexpected InterruptedException");
1239 jsr166 1.128 afe.initCause(fail);
1240 jsr166 1.60 throw afe;
1241     }
1242     }
1243    
1244     /**
1245 jsr166 1.88 * Spin-waits up to the specified number of milliseconds for the given
1246 jsr166 1.65 * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1247     */
1248     void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
1249 jsr166 1.88 long startTime = System.nanoTime();
1250 jsr166 1.65 for (;;) {
1251     Thread.State s = thread.getState();
1252     if (s == Thread.State.BLOCKED ||
1253     s == Thread.State.WAITING ||
1254 jsr166 1.67 s == Thread.State.TIMED_WAITING)
1255 jsr166 1.65 return;
1256 jsr166 1.67 else if (s == Thread.State.TERMINATED)
1257     fail("Unexpected thread termination");
1258 jsr166 1.88 else if (millisElapsedSince(startTime) > timeoutMillis) {
1259 jsr166 1.67 threadAssertTrue(thread.isAlive());
1260     return;
1261     }
1262 jsr166 1.65 Thread.yield();
1263     }
1264     }
1265    
1266     /**
1267 jsr166 1.75 * Waits up to LONG_DELAY_MS for the given thread to enter a wait
1268     * state: BLOCKED, WAITING, or TIMED_WAITING.
1269     */
1270     void waitForThreadToEnterWaitState(Thread thread) {
1271     waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
1272     }
1273    
1274     /**
1275 jsr166 1.66 * Returns the number of milliseconds since time given by
1276     * startNanoTime, which must have been previously returned from a
1277 jsr166 1.124 * call to {@link System#nanoTime()}.
1278 jsr166 1.66 */
1279 jsr166 1.117 static long millisElapsedSince(long startNanoTime) {
1280 jsr166 1.66 return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
1281     }
1282 jsr166 1.68
1283 jsr166 1.120 // void assertTerminatesPromptly(long timeoutMillis, Runnable r) {
1284     // long startTime = System.nanoTime();
1285     // try {
1286     // r.run();
1287     // } catch (Throwable fail) { threadUnexpectedException(fail); }
1288     // if (millisElapsedSince(startTime) > timeoutMillis/2)
1289     // throw new AssertionFailedError("did not return promptly");
1290     // }
1291    
1292     // void assertTerminatesPromptly(Runnable r) {
1293     // assertTerminatesPromptly(LONG_DELAY_MS/2, r);
1294     // }
1295    
1296     /**
1297     * Checks that timed f.get() returns the expected value, and does not
1298     * wait for the timeout to elapse before returning.
1299     */
1300     <T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) {
1301     long startTime = System.nanoTime();
1302     try {
1303     assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
1304     } catch (Throwable fail) { threadUnexpectedException(fail); }
1305     if (millisElapsedSince(startTime) > timeoutMillis/2)
1306     throw new AssertionFailedError("timed get did not return promptly");
1307     }
1308    
1309     <T> void checkTimedGet(Future<T> f, T expectedValue) {
1310     checkTimedGet(f, expectedValue, LONG_DELAY_MS);
1311     }
1312    
1313 jsr166 1.66 /**
1314 jsr166 1.58 * Returns a new started daemon Thread running the given runnable.
1315 jsr166 1.38 */
1316     Thread newStartedThread(Runnable runnable) {
1317     Thread t = new Thread(runnable);
1318 jsr166 1.58 t.setDaemon(true);
1319 jsr166 1.38 t.start();
1320     return t;
1321     }
1322 dl 1.1
1323 jsr166 1.59 /**
1324     * Waits for the specified time (in milliseconds) for the thread
1325     * to 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, long timeoutMillis) {
1329     try {
1330     t.join(timeoutMillis);
1331 jsr166 1.128 } catch (InterruptedException fail) {
1332     threadUnexpectedException(fail);
1333 jsr166 1.59 } finally {
1334 jsr166 1.83 if (t.getState() != Thread.State.TERMINATED) {
1335 jsr166 1.59 t.interrupt();
1336 jsr166 1.177 threadFail("timed out waiting for thread to terminate");
1337 jsr166 1.59 }
1338     }
1339     }
1340    
1341 jsr166 1.75 /**
1342     * Waits for LONG_DELAY_MS milliseconds for the thread to
1343     * terminate (using {@link Thread#join(long)}), else interrupts
1344     * the thread (in the hope that it may terminate later) and fails.
1345     */
1346     void awaitTermination(Thread t) {
1347     awaitTermination(t, LONG_DELAY_MS);
1348     }
1349    
1350 dl 1.1 // Some convenient Runnable classes
1351    
1352 jsr166 1.45 public abstract class CheckedRunnable implements Runnable {
1353     protected abstract void realRun() throws Throwable;
1354 jsr166 1.35
1355     public final void run() {
1356     try {
1357     realRun();
1358 jsr166 1.128 } catch (Throwable fail) {
1359     threadUnexpectedException(fail);
1360 jsr166 1.35 }
1361     }
1362     }
1363    
1364 jsr166 1.45 public abstract class RunnableShouldThrow implements Runnable {
1365     protected abstract void realRun() throws Throwable;
1366 jsr166 1.40
1367     final Class<?> exceptionClass;
1368    
1369     <T extends Throwable> RunnableShouldThrow(Class<T> exceptionClass) {
1370     this.exceptionClass = exceptionClass;
1371     }
1372    
1373     public final void run() {
1374     try {
1375     realRun();
1376     threadShouldThrow(exceptionClass.getSimpleName());
1377     } catch (Throwable t) {
1378     if (! exceptionClass.isInstance(t))
1379     threadUnexpectedException(t);
1380     }
1381     }
1382     }
1383    
1384 jsr166 1.45 public abstract class ThreadShouldThrow extends Thread {
1385     protected abstract void realRun() throws Throwable;
1386 jsr166 1.40
1387     final Class<?> exceptionClass;
1388    
1389     <T extends Throwable> ThreadShouldThrow(Class<T> exceptionClass) {
1390     this.exceptionClass = exceptionClass;
1391     }
1392    
1393     public final void run() {
1394     try {
1395     realRun();
1396     threadShouldThrow(exceptionClass.getSimpleName());
1397     } catch (Throwable t) {
1398     if (! exceptionClass.isInstance(t))
1399     threadUnexpectedException(t);
1400     }
1401     }
1402     }
1403    
1404 jsr166 1.45 public abstract class CheckedInterruptedRunnable implements Runnable {
1405     protected abstract void realRun() throws Throwable;
1406 jsr166 1.35
1407     public final void run() {
1408     try {
1409     realRun();
1410 jsr166 1.40 threadShouldThrow("InterruptedException");
1411 jsr166 1.35 } catch (InterruptedException success) {
1412 jsr166 1.81 threadAssertFalse(Thread.interrupted());
1413 jsr166 1.128 } catch (Throwable fail) {
1414     threadUnexpectedException(fail);
1415 jsr166 1.35 }
1416     }
1417     }
1418    
1419 jsr166 1.45 public abstract class CheckedCallable<T> implements Callable<T> {
1420     protected abstract T realCall() throws Throwable;
1421 jsr166 1.35
1422     public final T call() {
1423     try {
1424     return realCall();
1425 jsr166 1.128 } catch (Throwable fail) {
1426     threadUnexpectedException(fail);
1427 jsr166 1.53 return null;
1428 jsr166 1.35 }
1429 jsr166 1.40 }
1430     }
1431    
1432 jsr166 1.53 public abstract class CheckedInterruptedCallable<T>
1433     implements Callable<T> {
1434 jsr166 1.45 protected abstract T realCall() throws Throwable;
1435 jsr166 1.40
1436     public final T call() {
1437     try {
1438     T result = realCall();
1439     threadShouldThrow("InterruptedException");
1440     return result;
1441     } catch (InterruptedException success) {
1442 jsr166 1.81 threadAssertFalse(Thread.interrupted());
1443 jsr166 1.128 } catch (Throwable fail) {
1444     threadUnexpectedException(fail);
1445 jsr166 1.40 }
1446     return null;
1447 jsr166 1.35 }
1448     }
1449    
1450 jsr166 1.45 public static class NoOpRunnable implements Runnable {
1451 dl 1.1 public void run() {}
1452     }
1453    
1454 jsr166 1.45 public static class NoOpCallable implements Callable {
1455 dl 1.1 public Object call() { return Boolean.TRUE; }
1456 dl 1.10 }
1457    
1458 jsr166 1.45 public static final String TEST_STRING = "a test string";
1459 dl 1.10
1460 jsr166 1.45 public static class StringTask implements Callable<String> {
1461 jsr166 1.144 final String value;
1462     public StringTask() { this(TEST_STRING); }
1463     public StringTask(String value) { this.value = value; }
1464     public String call() { return value; }
1465 dl 1.10 }
1466    
1467 jsr166 1.48 public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
1468     return new CheckedCallable<String>() {
1469 jsr166 1.64 protected String realCall() {
1470 jsr166 1.48 try {
1471     latch.await();
1472     } catch (InterruptedException quittingTime) {}
1473     return TEST_STRING;
1474     }};
1475     }
1476    
1477 jsr166 1.148 public Runnable countDowner(final CountDownLatch latch) {
1478     return new CheckedRunnable() {
1479     public void realRun() throws InterruptedException {
1480     latch.countDown();
1481     }};
1482     }
1483    
1484 jsr166 1.161 class LatchAwaiter extends CheckedRunnable {
1485 jsr166 1.162 static final int NEW = 0;
1486     static final int RUNNING = 1;
1487     static final int DONE = 2;
1488 jsr166 1.161 final CountDownLatch latch;
1489     int state = NEW;
1490     LatchAwaiter(CountDownLatch latch) { this.latch = latch; }
1491     public void realRun() throws InterruptedException {
1492     state = 1;
1493     await(latch);
1494     state = 2;
1495     }
1496     }
1497 jsr166 1.162
1498 jsr166 1.161 public LatchAwaiter awaiter(CountDownLatch latch) {
1499     return new LatchAwaiter(latch);
1500 jsr166 1.73 }
1501    
1502 jsr166 1.188 public void await(CountDownLatch latch, long timeoutMillis) {
1503 jsr166 1.79 try {
1504 jsr166 1.188 if (!latch.await(timeoutMillis, MILLISECONDS))
1505 jsr166 1.176 fail("timed out waiting for CountDownLatch for "
1506 jsr166 1.188 + (timeoutMillis/1000) + " sec");
1507 jsr166 1.128 } catch (Throwable fail) {
1508     threadUnexpectedException(fail);
1509 jsr166 1.79 }
1510     }
1511    
1512 jsr166 1.188 public void await(CountDownLatch latch) {
1513     await(latch, LONG_DELAY_MS);
1514     }
1515    
1516 jsr166 1.89 public void await(Semaphore semaphore) {
1517     try {
1518 jsr166 1.176 if (!semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS))
1519     fail("timed out waiting for Semaphore for "
1520     + (LONG_DELAY_MS/1000) + " sec");
1521 jsr166 1.128 } catch (Throwable fail) {
1522     threadUnexpectedException(fail);
1523 jsr166 1.89 }
1524     }
1525    
1526 jsr166 1.81 // /**
1527     // * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1528     // */
1529     // public void await(AtomicBoolean flag) {
1530     // await(flag, LONG_DELAY_MS);
1531     // }
1532    
1533     // /**
1534     // * Spin-waits up to the specified timeout until flag becomes true.
1535     // */
1536     // public void await(AtomicBoolean flag, long timeoutMillis) {
1537     // long startTime = System.nanoTime();
1538     // while (!flag.get()) {
1539     // if (millisElapsedSince(startTime) > timeoutMillis)
1540     // throw new AssertionFailedError("timed out");
1541     // Thread.yield();
1542     // }
1543     // }
1544    
1545 jsr166 1.45 public static class NPETask implements Callable<String> {
1546 dl 1.10 public String call() { throw new NullPointerException(); }
1547     }
1548    
1549 jsr166 1.45 public static class CallableOne implements Callable<Integer> {
1550 dl 1.10 public Integer call() { return one; }
1551 dl 1.1 }
1552    
1553 jsr166 1.45 public class ShortRunnable extends CheckedRunnable {
1554     protected void realRun() throws Throwable {
1555 dl 1.76 delay(SHORT_DELAY_MS);
1556 dl 1.1 }
1557     }
1558    
1559 jsr166 1.45 public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1560     protected void realRun() throws InterruptedException {
1561 dl 1.76 delay(SHORT_DELAY_MS);
1562 dl 1.1 }
1563     }
1564    
1565 jsr166 1.45 public class SmallRunnable extends CheckedRunnable {
1566     protected void realRun() throws Throwable {
1567 dl 1.76 delay(SMALL_DELAY_MS);
1568 dl 1.1 }
1569     }
1570    
1571 jsr166 1.45 public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1572     protected void realRun() {
1573 dl 1.6 try {
1574 dl 1.76 delay(SMALL_DELAY_MS);
1575 jsr166 1.44 } catch (InterruptedException ok) {}
1576 dl 1.6 }
1577     }
1578    
1579 jsr166 1.45 public class SmallCallable extends CheckedCallable {
1580     protected Object realCall() throws InterruptedException {
1581 dl 1.76 delay(SMALL_DELAY_MS);
1582 dl 1.1 return Boolean.TRUE;
1583     }
1584     }
1585    
1586 jsr166 1.45 public class MediumRunnable extends CheckedRunnable {
1587     protected void realRun() throws Throwable {
1588 dl 1.76 delay(MEDIUM_DELAY_MS);
1589 dl 1.1 }
1590     }
1591    
1592 jsr166 1.45 public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1593     protected void realRun() throws InterruptedException {
1594 dl 1.76 delay(MEDIUM_DELAY_MS);
1595 dl 1.1 }
1596     }
1597    
1598 jsr166 1.63 public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1599     return new CheckedRunnable() {
1600     protected void realRun() {
1601     try {
1602 dl 1.76 delay(timeoutMillis);
1603 jsr166 1.63 } catch (InterruptedException ok) {}
1604     }};
1605     }
1606    
1607 jsr166 1.45 public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1608     protected void realRun() {
1609 dl 1.1 try {
1610 dl 1.76 delay(MEDIUM_DELAY_MS);
1611 jsr166 1.44 } catch (InterruptedException ok) {}
1612 dl 1.1 }
1613     }
1614 dl 1.5
1615 jsr166 1.45 public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1616     protected void realRun() {
1617 dl 1.12 try {
1618 dl 1.76 delay(LONG_DELAY_MS);
1619 jsr166 1.44 } catch (InterruptedException ok) {}
1620 dl 1.12 }
1621     }
1622    
1623 dl 1.5 /**
1624     * For use as ThreadFactory in constructors
1625     */
1626 jsr166 1.45 public static class SimpleThreadFactory implements ThreadFactory {
1627 jsr166 1.33 public Thread newThread(Runnable r) {
1628 dl 1.5 return new Thread(r);
1629 jsr166 1.27 }
1630 dl 1.5 }
1631    
1632 jsr166 1.61 public interface TrackedRunnable extends Runnable {
1633     boolean isDone();
1634     }
1635    
1636     public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
1637     return new TrackedRunnable() {
1638     private volatile boolean done = false;
1639     public boolean isDone() { return done; }
1640     public void run() {
1641     try {
1642 dl 1.76 delay(timeoutMillis);
1643 jsr166 1.61 done = true;
1644     } catch (InterruptedException ok) {}
1645     }
1646     };
1647     }
1648    
1649 jsr166 1.45 public static class TrackedShortRunnable implements Runnable {
1650     public volatile boolean done = false;
1651 dl 1.5 public void run() {
1652     try {
1653 dl 1.76 delay(SHORT_DELAY_MS);
1654 jsr166 1.61 done = true;
1655     } catch (InterruptedException ok) {}
1656     }
1657     }
1658    
1659     public static class TrackedSmallRunnable implements Runnable {
1660     public volatile boolean done = false;
1661     public void run() {
1662     try {
1663 dl 1.76 delay(SMALL_DELAY_MS);
1664 dl 1.5 done = true;
1665 jsr166 1.44 } catch (InterruptedException ok) {}
1666 dl 1.6 }
1667     }
1668    
1669 jsr166 1.45 public static class TrackedMediumRunnable implements Runnable {
1670     public volatile boolean done = false;
1671 dl 1.6 public void run() {
1672     try {
1673 dl 1.76 delay(MEDIUM_DELAY_MS);
1674 dl 1.6 done = true;
1675 jsr166 1.44 } catch (InterruptedException ok) {}
1676 dl 1.6 }
1677     }
1678    
1679 jsr166 1.45 public static class TrackedLongRunnable implements Runnable {
1680     public volatile boolean done = false;
1681 dl 1.6 public void run() {
1682     try {
1683 dl 1.76 delay(LONG_DELAY_MS);
1684 dl 1.6 done = true;
1685 jsr166 1.44 } catch (InterruptedException ok) {}
1686 dl 1.6 }
1687     }
1688    
1689 jsr166 1.45 public static class TrackedNoOpRunnable implements Runnable {
1690     public volatile boolean done = false;
1691 dl 1.6 public void run() {
1692     done = true;
1693 dl 1.5 }
1694     }
1695    
1696 jsr166 1.45 public static class TrackedCallable implements Callable {
1697     public volatile boolean done = false;
1698 dl 1.5 public Object call() {
1699     try {
1700 dl 1.76 delay(SMALL_DELAY_MS);
1701 dl 1.5 done = true;
1702 jsr166 1.44 } catch (InterruptedException ok) {}
1703 dl 1.5 return Boolean.TRUE;
1704     }
1705     }
1706 dl 1.14
1707 jsr166 1.53 /**
1708     * Analog of CheckedRunnable for RecursiveAction
1709     */
1710     public abstract class CheckedRecursiveAction extends RecursiveAction {
1711     protected abstract void realCompute() throws Throwable;
1712    
1713 jsr166 1.108 @Override protected final void compute() {
1714 jsr166 1.53 try {
1715     realCompute();
1716 jsr166 1.128 } catch (Throwable fail) {
1717     threadUnexpectedException(fail);
1718 jsr166 1.53 }
1719     }
1720     }
1721    
1722     /**
1723     * Analog of CheckedCallable for RecursiveTask
1724     */
1725     public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1726     protected abstract T realCompute() throws Throwable;
1727    
1728 jsr166 1.108 @Override protected final T compute() {
1729 jsr166 1.53 try {
1730     return realCompute();
1731 jsr166 1.128 } catch (Throwable fail) {
1732     threadUnexpectedException(fail);
1733 jsr166 1.53 return null;
1734     }
1735     }
1736     }
1737 dl 1.5
1738     /**
1739     * For use as RejectedExecutionHandler in constructors
1740     */
1741 jsr166 1.45 public static class NoOpREHandler implements RejectedExecutionHandler {
1742 jsr166 1.35 public void rejectedExecution(Runnable r,
1743     ThreadPoolExecutor executor) {}
1744 dl 1.5 }
1745 jsr166 1.27
1746 jsr166 1.60 /**
1747 jsr166 1.86 * A CyclicBarrier that uses timed await and fails with
1748     * AssertionFailedErrors instead of throwing checked exceptions.
1749 jsr166 1.60 */
1750     public class CheckedBarrier extends CyclicBarrier {
1751     public CheckedBarrier(int parties) { super(parties); }
1752    
1753     public int await() {
1754     try {
1755 jsr166 1.86 return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1756 jsr166 1.128 } catch (TimeoutException timedOut) {
1757 jsr166 1.86 throw new AssertionFailedError("timed out");
1758 jsr166 1.128 } catch (Exception fail) {
1759 jsr166 1.60 AssertionFailedError afe =
1760 jsr166 1.128 new AssertionFailedError("Unexpected exception: " + fail);
1761     afe.initCause(fail);
1762 jsr166 1.60 throw afe;
1763     }
1764     }
1765     }
1766    
1767 jsr166 1.81 void checkEmpty(BlockingQueue q) {
1768 jsr166 1.72 try {
1769     assertTrue(q.isEmpty());
1770     assertEquals(0, q.size());
1771     assertNull(q.peek());
1772     assertNull(q.poll());
1773     assertNull(q.poll(0, MILLISECONDS));
1774     assertEquals(q.toString(), "[]");
1775     assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1776     assertFalse(q.iterator().hasNext());
1777     try {
1778     q.element();
1779     shouldThrow();
1780     } catch (NoSuchElementException success) {}
1781     try {
1782     q.iterator().next();
1783     shouldThrow();
1784     } catch (NoSuchElementException success) {}
1785     try {
1786     q.remove();
1787     shouldThrow();
1788     } catch (NoSuchElementException success) {}
1789 jsr166 1.128 } catch (InterruptedException fail) { threadUnexpectedException(fail); }
1790 jsr166 1.72 }
1791    
1792 jsr166 1.91 void assertSerialEquals(Object x, Object y) {
1793     assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1794     }
1795    
1796     void assertNotSerialEquals(Object x, Object y) {
1797     assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1798     }
1799    
1800     byte[] serialBytes(Object o) {
1801 jsr166 1.79 try {
1802     ByteArrayOutputStream bos = new ByteArrayOutputStream();
1803     ObjectOutputStream oos = new ObjectOutputStream(bos);
1804     oos.writeObject(o);
1805     oos.flush();
1806     oos.close();
1807 jsr166 1.91 return bos.toByteArray();
1808 jsr166 1.128 } catch (Throwable fail) {
1809     threadUnexpectedException(fail);
1810 jsr166 1.91 return new byte[0];
1811     }
1812     }
1813    
1814     @SuppressWarnings("unchecked")
1815     <T> T serialClone(T o) {
1816     try {
1817 jsr166 1.87 ObjectInputStream ois = new ObjectInputStream
1818 jsr166 1.91 (new ByteArrayInputStream(serialBytes(o)));
1819 jsr166 1.87 T clone = (T) ois.readObject();
1820     assertSame(o.getClass(), clone.getClass());
1821     return clone;
1822 jsr166 1.128 } catch (Throwable fail) {
1823     threadUnexpectedException(fail);
1824 jsr166 1.79 return null;
1825     }
1826     }
1827 jsr166 1.106
1828     public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1829     Runnable... throwingActions) {
1830     for (Runnable throwingAction : throwingActions) {
1831     boolean threw = false;
1832     try { throwingAction.run(); }
1833     catch (Throwable t) {
1834     threw = true;
1835     if (!expectedExceptionClass.isInstance(t)) {
1836     AssertionFailedError afe =
1837     new AssertionFailedError
1838     ("Expected " + expectedExceptionClass.getName() +
1839     ", got " + t.getClass().getName());
1840     afe.initCause(t);
1841     threadUnexpectedException(afe);
1842     }
1843     }
1844     if (!threw)
1845     shouldThrow(expectedExceptionClass.getName());
1846     }
1847     }
1848 jsr166 1.126
1849     public void assertIteratorExhausted(Iterator<?> it) {
1850     try {
1851     it.next();
1852     shouldThrow();
1853     } catch (NoSuchElementException success) {}
1854     assertFalse(it.hasNext());
1855 jsr166 1.127 }
1856 jsr166 1.191
1857     public <T> Callable<T> callableThrowing(final Exception ex) {
1858     return new Callable<T>() { public T call() throws Exception { throw ex; }};
1859     }
1860    
1861     public Runnable runnableThrowing(final RuntimeException ex) {
1862     return new Runnable() { public void run() { throw ex; }};
1863     }
1864 jsr166 1.193
1865     /** A reusable thread pool to be shared by tests. */
1866     static final ExecutorService cachedThreadPool =
1867     new ThreadPoolExecutor(0, Integer.MAX_VALUE,
1868     1000L, MILLISECONDS,
1869     new SynchronousQueue<Runnable>());
1870    
1871 dl 1.1 }