ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.184
Committed: Wed Feb 10 00:05:20 2016 UTC (8 years, 2 months ago) by jsr166
Branch: MAIN
Changes since 1.183: +1 -0 lines
Log Message:
sync changes from 8149391: Fix module dependences in java/util tests

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