ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.182
Committed: Sun Jan 17 00:07:51 2016 UTC (8 years, 3 months ago) by jsr166
Branch: MAIN
Changes since 1.181: +7 -0 lines
Log Message:
allow tck tests to be run via jtreg junit support

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