ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.146
Committed: Fri Sep 25 23:32:15 2015 UTC (8 years, 7 months ago) by jsr166
Branch: MAIN
Changes since 1.145: +17 -6 lines
Log Message:
look much more aggressively for leaked threads in tearDown()

File Contents

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