ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.144
Committed: Mon Sep 14 03:14:01 2015 UTC (8 years, 7 months ago) by jsr166
Branch: MAIN
Changes since 1.143: +4 -1 lines
Log Message:
add constructor: new StringTask(value)

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