ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.189
Committed: Fri Mar 4 21:00:45 2016 UTC (8 years, 2 months ago) by jsr166
Branch: MAIN
Changes since 1.188: +25 -13 lines
Log Message:
improve handling of timeouts/delays; give fastdebug VMs more time by default

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