ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.219
Committed: Sat Feb 18 16:37:49 2017 UTC (7 years, 2 months ago) by jsr166
Branch: MAIN
Changes since 1.218: +43 -3 lines
Log Message:
waitForThreadToEnterWaitState should fail on timeout; tests should tolerate transient blocking Thread.State at any time (e.g. due to classloading)

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