ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.172
Committed: Fri Oct 9 01:26:36 2015 UTC (8 years, 6 months ago) by jsr166
Branch: MAIN
Changes since 1.171: +0 -3 lines
Log Message:
delete minor oops

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