ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.193
Committed: Mon May 23 18:19:48 2016 UTC (7 years, 11 months ago) by jsr166
Branch: MAIN
Changes since 1.192: +8 -0 lines
Log Message:
fix broken ant target tck-parallelism-0

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