ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.181
Committed: Mon Nov 9 06:06:54 2015 UTC (8 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.180: +9 -3 lines
Log Message:
add jsr166.delay.factor system property

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