ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.231
Committed: Mon May 15 17:02:46 2017 UTC (6 years, 11 months ago) by jsr166
Branch: MAIN
Changes since 1.230: +24 -0 lines
Log Message:
temporarily allow assertThreadsStayAlive to stay alive

File Contents

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