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 |
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; |
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; |
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; |
76 |
|
import java.util.concurrent.CountDownLatch; |
77 |
|
import java.util.concurrent.CyclicBarrier; |
78 |
|
import java.util.concurrent.ExecutionException; |
79 |
+ |
import java.util.concurrent.Executor; |
80 |
|
import java.util.concurrent.Executors; |
81 |
|
import java.util.concurrent.ExecutorService; |
82 |
|
import java.util.concurrent.ForkJoinPool; |
83 |
|
import java.util.concurrent.Future; |
84 |
+ |
import java.util.concurrent.FutureTask; |
85 |
|
import java.util.concurrent.RecursiveAction; |
86 |
|
import java.util.concurrent.RecursiveTask; |
87 |
+ |
import java.util.concurrent.RejectedExecutionException; |
88 |
|
import java.util.concurrent.RejectedExecutionHandler; |
89 |
|
import java.util.concurrent.Semaphore; |
90 |
+ |
import java.util.concurrent.ScheduledExecutorService; |
91 |
+ |
import java.util.concurrent.ScheduledFuture; |
92 |
+ |
import java.util.concurrent.SynchronousQueue; |
93 |
|
import java.util.concurrent.ThreadFactory; |
94 |
+ |
import java.util.concurrent.ThreadLocalRandom; |
95 |
|
import java.util.concurrent.ThreadPoolExecutor; |
96 |
+ |
import java.util.concurrent.TimeUnit; |
97 |
|
import java.util.concurrent.TimeoutException; |
98 |
+ |
import java.util.concurrent.atomic.AtomicBoolean; |
99 |
|
import java.util.concurrent.atomic.AtomicReference; |
100 |
|
import java.util.regex.Pattern; |
101 |
|
|
154 |
|
* methods as there are exceptions the method can throw. Sometimes |
155 |
|
* there are multiple tests per JSR166 method when the different |
156 |
|
* "normal" behaviors differ significantly. And sometimes testcases |
157 |
< |
* cover multiple methods when they cannot be tested in |
111 |
< |
* isolation. |
157 |
> |
* cover multiple methods when they cannot be tested in isolation. |
158 |
|
* |
159 |
|
* <li>The documentation style for testcases is to provide as javadoc |
160 |
|
* a simple sentence or two describing the property that the testcase |
217 |
|
private static final int suiteRuns = |
218 |
|
Integer.getInteger("jsr166.suiteRuns", 1); |
219 |
|
|
220 |
+ |
/** |
221 |
+ |
* Returns the value of the system property, or NaN if not defined. |
222 |
+ |
*/ |
223 |
+ |
private static float systemPropertyValue(String name) { |
224 |
+ |
String floatString = System.getProperty(name); |
225 |
+ |
if (floatString == null) |
226 |
+ |
return Float.NaN; |
227 |
+ |
try { |
228 |
+ |
return Float.parseFloat(floatString); |
229 |
+ |
} catch (NumberFormatException ex) { |
230 |
+ |
throw new IllegalArgumentException( |
231 |
+ |
String.format("Bad float value in system property %s=%s", |
232 |
+ |
name, floatString)); |
233 |
+ |
} |
234 |
+ |
} |
235 |
+ |
|
236 |
+ |
/** |
237 |
+ |
* The scaling factor to apply to standard delays used in tests. |
238 |
+ |
* May be initialized from any of: |
239 |
+ |
* - the "jsr166.delay.factor" system property |
240 |
+ |
* - the "test.timeout.factor" system property (as used by jtreg) |
241 |
+ |
* See: http://openjdk.java.net/jtreg/tag-spec.html |
242 |
+ |
* - hard-coded fuzz factor when using a known slowpoke VM |
243 |
+ |
*/ |
244 |
+ |
private static final float delayFactor = delayFactor(); |
245 |
+ |
|
246 |
+ |
private static float delayFactor() { |
247 |
+ |
float x; |
248 |
+ |
if (!Float.isNaN(x = systemPropertyValue("jsr166.delay.factor"))) |
249 |
+ |
return x; |
250 |
+ |
if (!Float.isNaN(x = systemPropertyValue("test.timeout.factor"))) |
251 |
+ |
return x; |
252 |
+ |
String prop = System.getProperty("java.vm.version"); |
253 |
+ |
if (prop != null && prop.matches(".*debug.*")) |
254 |
+ |
return 4.0f; // How much slower is fastdebug than product?! |
255 |
+ |
return 1.0f; |
256 |
+ |
} |
257 |
+ |
|
258 |
|
public JSR166TestCase() { super(); } |
259 |
|
public JSR166TestCase(String name) { super(name); } |
260 |
|
|
270 |
|
return (regex == null) ? null : Pattern.compile(regex); |
271 |
|
} |
272 |
|
|
273 |
+ |
// Instrumentation to debug very rare, but very annoying hung test runs. |
274 |
+ |
static volatile TestCase currentTestCase; |
275 |
+ |
// static volatile int currentRun = 0; |
276 |
+ |
static { |
277 |
+ |
Runnable checkForWedgedTest = new Runnable() { public void run() { |
278 |
+ |
// Avoid spurious reports with enormous runsPerTest. |
279 |
+ |
// A single test case run should never take more than 1 second. |
280 |
+ |
// But let's cap it at the high end too ... |
281 |
+ |
final int timeoutMinutes = |
282 |
+ |
Math.min(15, Math.max(runsPerTest / 60, 1)); |
283 |
+ |
for (TestCase lastTestCase = currentTestCase;;) { |
284 |
+ |
try { MINUTES.sleep(timeoutMinutes); } |
285 |
+ |
catch (InterruptedException unexpected) { break; } |
286 |
+ |
if (lastTestCase == currentTestCase) { |
287 |
+ |
System.err.printf( |
288 |
+ |
"Looks like we're stuck running test: %s%n", |
289 |
+ |
lastTestCase); |
290 |
+ |
// System.err.printf( |
291 |
+ |
// "Looks like we're stuck running test: %s (%d/%d)%n", |
292 |
+ |
// lastTestCase, currentRun, runsPerTest); |
293 |
+ |
// System.err.println("availableProcessors=" + |
294 |
+ |
// Runtime.getRuntime().availableProcessors()); |
295 |
+ |
// System.err.printf("cpu model = %s%n", cpuModel()); |
296 |
+ |
dumpTestThreads(); |
297 |
+ |
// one stack dump is probably enough; more would be spam |
298 |
+ |
break; |
299 |
+ |
} |
300 |
+ |
lastTestCase = currentTestCase; |
301 |
+ |
}}}; |
302 |
+ |
Thread thread = new Thread(checkForWedgedTest, "checkForWedgedTest"); |
303 |
+ |
thread.setDaemon(true); |
304 |
+ |
thread.start(); |
305 |
+ |
} |
306 |
+ |
|
307 |
+ |
// public static String cpuModel() { |
308 |
+ |
// try { |
309 |
+ |
// java.util.regex.Matcher matcher |
310 |
+ |
// = Pattern.compile("model name\\s*: (.*)") |
311 |
+ |
// .matcher(new String( |
312 |
+ |
// java.nio.file.Files.readAllBytes( |
313 |
+ |
// java.nio.file.Paths.get("/proc/cpuinfo")), "UTF-8")); |
314 |
+ |
// matcher.find(); |
315 |
+ |
// return matcher.group(1); |
316 |
+ |
// } catch (Exception ex) { return null; } |
317 |
+ |
// } |
318 |
+ |
|
319 |
|
public void runBare() throws Throwable { |
320 |
+ |
currentTestCase = this; |
321 |
|
if (methodFilter == null |
322 |
|
|| methodFilter.matcher(toString()).find()) |
323 |
|
super.runBare(); |
325 |
|
|
326 |
|
protected void runTest() throws Throwable { |
327 |
|
for (int i = 0; i < runsPerTest; i++) { |
328 |
+ |
// currentRun = i; |
329 |
|
if (profileTests) |
330 |
|
runTestProfiled(); |
331 |
|
else |
354 |
|
main(suite(), args); |
355 |
|
} |
356 |
|
|
357 |
+ |
static class PithyResultPrinter extends junit.textui.ResultPrinter { |
358 |
+ |
PithyResultPrinter(java.io.PrintStream writer) { super(writer); } |
359 |
+ |
long runTime; |
360 |
+ |
public void startTest(Test test) {} |
361 |
+ |
protected void printHeader(long runTime) { |
362 |
+ |
this.runTime = runTime; // defer printing for later |
363 |
+ |
} |
364 |
+ |
protected void printFooter(TestResult result) { |
365 |
+ |
if (result.wasSuccessful()) { |
366 |
+ |
getWriter().println("OK (" + result.runCount() + " tests)" |
367 |
+ |
+ " Time: " + elapsedTimeAsString(runTime)); |
368 |
+ |
} else { |
369 |
+ |
getWriter().println("Time: " + elapsedTimeAsString(runTime)); |
370 |
+ |
super.printFooter(result); |
371 |
+ |
} |
372 |
+ |
} |
373 |
+ |
} |
374 |
+ |
|
375 |
+ |
/** |
376 |
+ |
* Returns a TestRunner that doesn't bother with unnecessary |
377 |
+ |
* fluff, like printing a "." for each test case. |
378 |
+ |
*/ |
379 |
+ |
static junit.textui.TestRunner newPithyTestRunner() { |
380 |
+ |
junit.textui.TestRunner runner = new junit.textui.TestRunner(); |
381 |
+ |
runner.setPrinter(new PithyResultPrinter(System.out)); |
382 |
+ |
return runner; |
383 |
+ |
} |
384 |
+ |
|
385 |
|
/** |
386 |
|
* Runs all unit tests in the given test suite. |
387 |
|
* Actual behavior influenced by jsr166.* system properties. |
393 |
|
System.setSecurityManager(new SecurityManager()); |
394 |
|
} |
395 |
|
for (int i = 0; i < suiteRuns; i++) { |
396 |
< |
TestResult result = junit.textui.TestRunner.run(suite); |
396 |
> |
TestResult result = newPithyTestRunner().doRun(suite); |
397 |
|
if (!result.wasSuccessful()) |
398 |
|
System.exit(1); |
399 |
|
System.gc(); |
477 |
|
AbstractQueuedLongSynchronizerTest.suite(), |
478 |
|
ArrayBlockingQueueTest.suite(), |
479 |
|
ArrayDequeTest.suite(), |
480 |
+ |
ArrayListTest.suite(), |
481 |
|
AtomicBooleanTest.suite(), |
482 |
|
AtomicIntegerArrayTest.suite(), |
483 |
|
AtomicIntegerFieldUpdaterTest.suite(), |
500 |
|
CopyOnWriteArrayListTest.suite(), |
501 |
|
CopyOnWriteArraySetTest.suite(), |
502 |
|
CountDownLatchTest.suite(), |
503 |
+ |
CountedCompleterTest.suite(), |
504 |
|
CyclicBarrierTest.suite(), |
505 |
|
DelayQueueTest.suite(), |
506 |
|
EntryTest.suite(), |
529 |
|
TreeMapTest.suite(), |
530 |
|
TreeSetTest.suite(), |
531 |
|
TreeSubMapTest.suite(), |
532 |
< |
TreeSubSetTest.suite()); |
532 |
> |
TreeSubSetTest.suite(), |
533 |
> |
VectorTest.suite()); |
534 |
|
|
535 |
|
// Java8+ test classes |
536 |
|
if (atLeastJava8()) { |
537 |
|
String[] java8TestClassNames = { |
538 |
+ |
"ArrayDeque8Test", |
539 |
|
"Atomic8Test", |
540 |
|
"CompletableFutureTest", |
541 |
|
"ConcurrentHashMap8Test", |
542 |
< |
"CountedCompleterTest", |
542 |
> |
"CountedCompleter8Test", |
543 |
|
"DoubleAccumulatorTest", |
544 |
|
"DoubleAdderTest", |
545 |
|
"ForkJoinPool8Test", |
546 |
|
"ForkJoinTask8Test", |
547 |
+ |
"LinkedBlockingDeque8Test", |
548 |
+ |
"LinkedBlockingQueue8Test", |
549 |
|
"LongAccumulatorTest", |
550 |
|
"LongAdderTest", |
551 |
|
"SplittableRandomTest", |
552 |
|
"StampedLockTest", |
553 |
|
"SubmissionPublisherTest", |
554 |
|
"ThreadLocalRandom8Test", |
555 |
+ |
"TimeUnit8Test", |
556 |
|
}; |
557 |
|
addNamedTestClasses(suite, java8TestClassNames); |
558 |
|
} |
560 |
|
// Java9+ test classes |
561 |
|
if (atLeastJava9()) { |
562 |
|
String[] java9TestClassNames = { |
563 |
< |
// Currently empty, but expecting varhandle tests |
563 |
> |
"AtomicBoolean9Test", |
564 |
> |
"AtomicInteger9Test", |
565 |
> |
"AtomicIntegerArray9Test", |
566 |
> |
"AtomicLong9Test", |
567 |
> |
"AtomicLongArray9Test", |
568 |
> |
"AtomicReference9Test", |
569 |
> |
"AtomicReferenceArray9Test", |
570 |
> |
"ExecutorCompletionService9Test", |
571 |
> |
"ForkJoinPool9Test", |
572 |
|
}; |
573 |
|
addNamedTestClasses(suite, java9TestClassNames); |
574 |
|
} |
579 |
|
/** Returns list of junit-style test method names in given class. */ |
580 |
|
public static ArrayList<String> testMethodNames(Class<?> testClass) { |
581 |
|
Method[] methods = testClass.getDeclaredMethods(); |
582 |
< |
ArrayList<String> names = new ArrayList<String>(methods.length); |
582 |
> |
ArrayList<String> names = new ArrayList<>(methods.length); |
583 |
|
for (Method method : methods) { |
584 |
|
if (method.getName().startsWith("test") |
585 |
|
&& Modifier.isPublic(method.getModifiers()) |
635 |
|
} else { |
636 |
|
return new TestSuite(); |
637 |
|
} |
463 |
– |
|
638 |
|
} |
639 |
|
|
640 |
|
// Delays for timing-dependent tests, in milliseconds. |
644 |
|
public static long MEDIUM_DELAY_MS; |
645 |
|
public static long LONG_DELAY_MS; |
646 |
|
|
647 |
+ |
private static final long RANDOM_TIMEOUT; |
648 |
+ |
private static final long RANDOM_EXPIRED_TIMEOUT; |
649 |
+ |
private static final TimeUnit RANDOM_TIMEUNIT; |
650 |
+ |
static { |
651 |
+ |
ThreadLocalRandom rnd = ThreadLocalRandom.current(); |
652 |
+ |
long[] timeouts = { Long.MIN_VALUE, -1, 0, 1, Long.MAX_VALUE }; |
653 |
+ |
RANDOM_TIMEOUT = timeouts[rnd.nextInt(timeouts.length)]; |
654 |
+ |
RANDOM_EXPIRED_TIMEOUT = timeouts[rnd.nextInt(3)]; |
655 |
+ |
TimeUnit[] timeUnits = TimeUnit.values(); |
656 |
+ |
RANDOM_TIMEUNIT = timeUnits[rnd.nextInt(timeUnits.length)]; |
657 |
+ |
} |
658 |
+ |
|
659 |
+ |
/** |
660 |
+ |
* Returns a timeout for use when any value at all will do. |
661 |
+ |
*/ |
662 |
+ |
static long randomTimeout() { return RANDOM_TIMEOUT; } |
663 |
+ |
|
664 |
+ |
/** |
665 |
+ |
* Returns a timeout that means "no waiting", i.e. not positive. |
666 |
+ |
*/ |
667 |
+ |
static long randomExpiredTimeout() { return RANDOM_EXPIRED_TIMEOUT; } |
668 |
+ |
|
669 |
|
/** |
670 |
< |
* Returns the shortest timed delay. This could |
671 |
< |
* be reimplemented to use for example a Property. |
670 |
> |
* Returns a random non-null TimeUnit. |
671 |
> |
*/ |
672 |
> |
static TimeUnit randomTimeUnit() { return RANDOM_TIMEUNIT; } |
673 |
> |
|
674 |
> |
/** |
675 |
> |
* Returns the shortest timed delay. This can be scaled up for |
676 |
> |
* slow machines using the jsr166.delay.factor system property, |
677 |
> |
* or via jtreg's -timeoutFactor: flag. |
678 |
> |
* http://openjdk.java.net/jtreg/command-help.html |
679 |
|
*/ |
680 |
|
protected long getShortDelay() { |
681 |
< |
return 50; |
681 |
> |
return (long) (50 * delayFactor); |
682 |
|
} |
683 |
|
|
684 |
|
/** |
691 |
|
LONG_DELAY_MS = SHORT_DELAY_MS * 200; |
692 |
|
} |
693 |
|
|
694 |
+ |
private static final long TIMEOUT_DELAY_MS |
695 |
+ |
= (long) (12.0 * Math.cbrt(delayFactor)); |
696 |
+ |
|
697 |
|
/** |
698 |
< |
* Returns a timeout in milliseconds to be used in tests that |
699 |
< |
* verify that operations block or time out. |
698 |
> |
* Returns a timeout in milliseconds to be used in tests that verify |
699 |
> |
* that operations block or time out. We want this to be longer |
700 |
> |
* than the OS scheduling quantum, but not too long, so don't scale |
701 |
> |
* linearly with delayFactor; we use "crazy" cube root instead. |
702 |
|
*/ |
703 |
< |
long timeoutMillis() { |
704 |
< |
return SHORT_DELAY_MS / 4; |
703 |
> |
static long timeoutMillis() { |
704 |
> |
return TIMEOUT_DELAY_MS; |
705 |
|
} |
706 |
|
|
707 |
|
/** |
717 |
|
* The first exception encountered if any threadAssertXXX method fails. |
718 |
|
*/ |
719 |
|
private final AtomicReference<Throwable> threadFailure |
720 |
< |
= new AtomicReference<Throwable>(null); |
720 |
> |
= new AtomicReference<>(null); |
721 |
|
|
722 |
|
/** |
723 |
|
* Records an exception so that it can be rethrown later in the test |
726 |
|
* the same test have no effect. |
727 |
|
*/ |
728 |
|
public void threadRecordFailure(Throwable t) { |
729 |
+ |
System.err.println(t); |
730 |
+ |
dumpTestThreads(); |
731 |
|
threadFailure.compareAndSet(null, t); |
732 |
|
} |
733 |
|
|
738 |
|
void tearDownFail(String format, Object... args) { |
739 |
|
String msg = toString() + ": " + String.format(format, args); |
740 |
|
System.err.println(msg); |
741 |
< |
printAllStackTraces(); |
741 |
> |
dumpTestThreads(); |
742 |
|
throw new AssertionFailedError(msg); |
743 |
|
} |
744 |
|
|
775 |
|
} |
776 |
|
|
777 |
|
/** |
778 |
< |
* Finds missing try { ... } finally { joinPool(e); } |
778 |
> |
* Finds missing PoolCleaners |
779 |
|
*/ |
780 |
|
void checkForkJoinPoolThreadLeaks() throws InterruptedException { |
781 |
|
Thread[] survivors = new Thread[7]; |
807 |
|
fail(reason); |
808 |
|
} catch (AssertionFailedError t) { |
809 |
|
threadRecordFailure(t); |
810 |
< |
fail(reason); |
810 |
> |
throw t; |
811 |
|
} |
812 |
|
} |
813 |
|
|
934 |
|
/** |
935 |
|
* Delays, via Thread.sleep, for the given millisecond delay, but |
936 |
|
* if the sleep is shorter than specified, may re-sleep or yield |
937 |
< |
* until time elapses. |
937 |
> |
* until time elapses. Ensures that the given time, as measured |
938 |
> |
* by System.nanoTime(), has elapsed. |
939 |
|
*/ |
940 |
|
static void delay(long millis) throws InterruptedException { |
941 |
< |
long startTime = System.nanoTime(); |
942 |
< |
long ns = millis * 1000 * 1000; |
943 |
< |
for (;;) { |
941 |
> |
long nanos = millis * (1000 * 1000); |
942 |
> |
final long wakeupTime = System.nanoTime() + nanos; |
943 |
> |
do { |
944 |
|
if (millis > 0L) |
945 |
|
Thread.sleep(millis); |
946 |
|
else // too short to sleep |
947 |
|
Thread.yield(); |
948 |
< |
long d = ns - (System.nanoTime() - startTime); |
949 |
< |
if (d > 0L) |
950 |
< |
millis = d / (1000 * 1000); |
951 |
< |
else |
952 |
< |
break; |
948 |
> |
nanos = wakeupTime - System.nanoTime(); |
949 |
> |
millis = nanos / (1000 * 1000); |
950 |
> |
} while (nanos >= 0L); |
951 |
> |
} |
952 |
> |
|
953 |
> |
/** |
954 |
> |
* Allows use of try-with-resources with per-test thread pools. |
955 |
> |
*/ |
956 |
> |
class PoolCleaner implements AutoCloseable { |
957 |
> |
private final ExecutorService pool; |
958 |
> |
public PoolCleaner(ExecutorService pool) { this.pool = pool; } |
959 |
> |
public void close() { joinPool(pool); } |
960 |
> |
} |
961 |
> |
|
962 |
> |
/** |
963 |
> |
* An extension of PoolCleaner that has an action to release the pool. |
964 |
> |
*/ |
965 |
> |
class PoolCleanerWithReleaser extends PoolCleaner { |
966 |
> |
private final Runnable releaser; |
967 |
> |
public PoolCleanerWithReleaser(ExecutorService pool, Runnable releaser) { |
968 |
> |
super(pool); |
969 |
> |
this.releaser = releaser; |
970 |
> |
} |
971 |
> |
public void close() { |
972 |
> |
try { |
973 |
> |
releaser.run(); |
974 |
> |
} finally { |
975 |
> |
super.close(); |
976 |
> |
} |
977 |
|
} |
978 |
|
} |
979 |
|
|
980 |
+ |
PoolCleaner cleaner(ExecutorService pool) { |
981 |
+ |
return new PoolCleaner(pool); |
982 |
+ |
} |
983 |
+ |
|
984 |
+ |
PoolCleaner cleaner(ExecutorService pool, Runnable releaser) { |
985 |
+ |
return new PoolCleanerWithReleaser(pool, releaser); |
986 |
+ |
} |
987 |
+ |
|
988 |
+ |
PoolCleaner cleaner(ExecutorService pool, CountDownLatch latch) { |
989 |
+ |
return new PoolCleanerWithReleaser(pool, releaser(latch)); |
990 |
+ |
} |
991 |
+ |
|
992 |
+ |
Runnable releaser(final CountDownLatch latch) { |
993 |
+ |
return new Runnable() { public void run() { |
994 |
+ |
do { latch.countDown(); } |
995 |
+ |
while (latch.getCount() > 0); |
996 |
+ |
}}; |
997 |
+ |
} |
998 |
+ |
|
999 |
+ |
PoolCleaner cleaner(ExecutorService pool, AtomicBoolean flag) { |
1000 |
+ |
return new PoolCleanerWithReleaser(pool, releaser(flag)); |
1001 |
+ |
} |
1002 |
+ |
|
1003 |
+ |
Runnable releaser(final AtomicBoolean flag) { |
1004 |
+ |
return new Runnable() { public void run() { flag.set(true); }}; |
1005 |
+ |
} |
1006 |
+ |
|
1007 |
|
/** |
1008 |
|
* Waits out termination of a thread pool or fails doing so. |
1009 |
|
*/ |
1010 |
|
void joinPool(ExecutorService pool) { |
1011 |
|
try { |
1012 |
|
pool.shutdown(); |
1013 |
< |
if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS)) |
1014 |
< |
fail("ExecutorService " + pool + |
1015 |
< |
" did not terminate in a timely manner"); |
1013 |
> |
if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS)) { |
1014 |
> |
try { |
1015 |
> |
threadFail("ExecutorService " + pool + |
1016 |
> |
" did not terminate in a timely manner"); |
1017 |
> |
} finally { |
1018 |
> |
// last resort, for the benefit of subsequent tests |
1019 |
> |
pool.shutdownNow(); |
1020 |
> |
pool.awaitTermination(MEDIUM_DELAY_MS, MILLISECONDS); |
1021 |
> |
} |
1022 |
> |
} |
1023 |
|
} catch (SecurityException ok) { |
1024 |
|
// Allowed in case test doesn't have privs |
1025 |
|
} catch (InterruptedException fail) { |
1026 |
< |
fail("Unexpected InterruptedException"); |
1026 |
> |
threadFail("Unexpected InterruptedException"); |
1027 |
|
} |
1028 |
|
} |
1029 |
|
|
1030 |
< |
/** Like Runnable, but with the freedom to throw anything */ |
1030 |
> |
/** |
1031 |
> |
* Like Runnable, but with the freedom to throw anything. |
1032 |
> |
* junit folks had the same idea: |
1033 |
> |
* http://junit.org/junit5/docs/snapshot/api/org/junit/gen5/api/Executable.html |
1034 |
> |
*/ |
1035 |
|
interface Action { public void run() throws Throwable; } |
1036 |
|
|
1037 |
|
/** |
1041 |
|
*/ |
1042 |
|
void testInParallel(Action ... actions) { |
1043 |
|
ExecutorService pool = Executors.newCachedThreadPool(); |
1044 |
< |
try { |
1044 |
> |
try (PoolCleaner cleaner = cleaner(pool)) { |
1045 |
|
ArrayList<Future<?>> futures = new ArrayList<>(actions.length); |
1046 |
|
for (final Action action : actions) |
1047 |
|
futures.add(pool.submit(new CheckedRunnable() { |
1054 |
|
} catch (Exception ex) { |
1055 |
|
threadUnexpectedException(ex); |
1056 |
|
} |
784 |
– |
} finally { |
785 |
– |
joinPool(pool); |
1057 |
|
} |
1058 |
|
} |
1059 |
|
|
1060 |
|
/** |
1061 |
< |
* A debugging tool to print all stack traces, as jstack does. |
1062 |
< |
*/ |
792 |
< |
static void printAllStackTraces() { |
793 |
< |
for (ThreadInfo info : |
794 |
< |
ManagementFactory.getThreadMXBean() |
795 |
< |
.dumpAllThreads(true, true)) |
796 |
< |
System.err.print(info); |
797 |
< |
} |
798 |
< |
|
799 |
< |
/** |
800 |
< |
* Checks that thread does not terminate within the default |
801 |
< |
* millisecond delay of {@code timeoutMillis()}. |
1061 |
> |
* A debugging tool to print stack traces of most threads, as jstack does. |
1062 |
> |
* Uninteresting threads are filtered out. |
1063 |
|
*/ |
1064 |
< |
void assertThreadStaysAlive(Thread thread) { |
1065 |
< |
assertThreadStaysAlive(thread, timeoutMillis()); |
1066 |
< |
} |
1064 |
> |
static void dumpTestThreads() { |
1065 |
> |
SecurityManager sm = System.getSecurityManager(); |
1066 |
> |
if (sm != null) { |
1067 |
> |
try { |
1068 |
> |
System.setSecurityManager(null); |
1069 |
> |
} catch (SecurityException giveUp) { |
1070 |
> |
return; |
1071 |
> |
} |
1072 |
> |
} |
1073 |
|
|
1074 |
< |
/** |
1075 |
< |
* Checks that thread does not terminate within the given millisecond delay. |
1076 |
< |
*/ |
1077 |
< |
void assertThreadStaysAlive(Thread thread, long millis) { |
1078 |
< |
try { |
1079 |
< |
// No need to optimize the failing case via Thread.join. |
1080 |
< |
delay(millis); |
1081 |
< |
assertTrue(thread.isAlive()); |
1082 |
< |
} catch (InterruptedException fail) { |
1083 |
< |
fail("Unexpected InterruptedException"); |
1074 |
> |
ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); |
1075 |
> |
System.err.println("------ stacktrace dump start ------"); |
1076 |
> |
for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) { |
1077 |
> |
final String name = info.getThreadName(); |
1078 |
> |
String lockName; |
1079 |
> |
if ("Signal Dispatcher".equals(name)) |
1080 |
> |
continue; |
1081 |
> |
if ("Reference Handler".equals(name) |
1082 |
> |
&& (lockName = info.getLockName()) != null |
1083 |
> |
&& lockName.startsWith("java.lang.ref.Reference$Lock")) |
1084 |
> |
continue; |
1085 |
> |
if ("Finalizer".equals(name) |
1086 |
> |
&& (lockName = info.getLockName()) != null |
1087 |
> |
&& lockName.startsWith("java.lang.ref.ReferenceQueue$Lock")) |
1088 |
> |
continue; |
1089 |
> |
if ("checkForWedgedTest".equals(name)) |
1090 |
> |
continue; |
1091 |
> |
System.err.print(info); |
1092 |
|
} |
1093 |
< |
} |
1093 |
> |
System.err.println("------ stacktrace dump end ------"); |
1094 |
|
|
1095 |
< |
/** |
821 |
< |
* Checks that the threads do not terminate within the default |
822 |
< |
* millisecond delay of {@code timeoutMillis()}. |
823 |
< |
*/ |
824 |
< |
void assertThreadsStayAlive(Thread... threads) { |
825 |
< |
assertThreadsStayAlive(timeoutMillis(), threads); |
1095 |
> |
if (sm != null) System.setSecurityManager(sm); |
1096 |
|
} |
1097 |
|
|
1098 |
|
/** |
1099 |
< |
* Checks that the threads do not terminate within the given millisecond delay. |
1099 |
> |
* Checks that thread eventually enters the expected blocked thread state. |
1100 |
|
*/ |
1101 |
< |
void assertThreadsStayAlive(long millis, Thread... threads) { |
1102 |
< |
try { |
1103 |
< |
// No need to optimize the failing case via Thread.join. |
1104 |
< |
delay(millis); |
1105 |
< |
for (Thread thread : threads) |
1106 |
< |
assertTrue(thread.isAlive()); |
1107 |
< |
} catch (InterruptedException fail) { |
1108 |
< |
fail("Unexpected InterruptedException"); |
1101 |
> |
void assertThreadBlocks(Thread thread, Thread.State expected) { |
1102 |
> |
// always sleep at least 1 ms, with high probability avoiding |
1103 |
> |
// transitory states |
1104 |
> |
for (long retries = LONG_DELAY_MS * 3 / 4; retries-->0; ) { |
1105 |
> |
try { delay(1); } |
1106 |
> |
catch (InterruptedException fail) { |
1107 |
> |
fail("Unexpected InterruptedException"); |
1108 |
> |
} |
1109 |
> |
Thread.State s = thread.getState(); |
1110 |
> |
if (s == expected) |
1111 |
> |
return; |
1112 |
> |
else if (s == Thread.State.TERMINATED) |
1113 |
> |
fail("Unexpected thread termination"); |
1114 |
|
} |
1115 |
+ |
fail("timed out waiting for thread to enter thread state " + expected); |
1116 |
|
} |
1117 |
|
|
1118 |
|
/** |
1153 |
|
} |
1154 |
|
|
1155 |
|
/** |
1156 |
+ |
* The maximum number of consecutive spurious wakeups we should |
1157 |
+ |
* tolerate (from APIs like LockSupport.park) before failing a test. |
1158 |
+ |
*/ |
1159 |
+ |
static final int MAX_SPURIOUS_WAKEUPS = 10; |
1160 |
+ |
|
1161 |
+ |
/** |
1162 |
|
* The number of elements to place in collections, arrays, etc. |
1163 |
|
*/ |
1164 |
|
public static final int SIZE = 20; |
1262 |
|
} |
1263 |
|
public void refresh() {} |
1264 |
|
public String toString() { |
1265 |
< |
List<Permission> ps = new ArrayList<Permission>(); |
1265 |
> |
List<Permission> ps = new ArrayList<>(); |
1266 |
|
for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();) |
1267 |
|
ps.add(e.nextElement()); |
1268 |
|
return "AdjustablePolicy with permissions " + ps; |
1292 |
|
* Sleeps until the given time has elapsed. |
1293 |
|
* Throws AssertionFailedError if interrupted. |
1294 |
|
*/ |
1295 |
< |
void sleep(long millis) { |
1295 |
> |
static void sleep(long millis) { |
1296 |
|
try { |
1297 |
|
delay(millis); |
1298 |
|
} catch (InterruptedException fail) { |
1308 |
|
* thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING. |
1309 |
|
*/ |
1310 |
|
void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) { |
1311 |
< |
long startTime = System.nanoTime(); |
1311 |
> |
long startTime = 0L; |
1312 |
|
for (;;) { |
1313 |
|
Thread.State s = thread.getState(); |
1314 |
|
if (s == Thread.State.BLOCKED || |
1317 |
|
return; |
1318 |
|
else if (s == Thread.State.TERMINATED) |
1319 |
|
fail("Unexpected thread termination"); |
1320 |
+ |
else if (startTime == 0L) |
1321 |
+ |
startTime = System.nanoTime(); |
1322 |
|
else if (millisElapsedSince(startTime) > timeoutMillis) { |
1323 |
|
threadAssertTrue(thread.isAlive()); |
1324 |
< |
return; |
1324 |
> |
fail("timed out waiting for thread to enter wait state"); |
1325 |
|
} |
1326 |
|
Thread.yield(); |
1327 |
|
} |
1328 |
|
} |
1329 |
|
|
1330 |
|
/** |
1331 |
< |
* Waits up to LONG_DELAY_MS for the given thread to enter a wait |
1332 |
< |
* state: BLOCKED, WAITING, or TIMED_WAITING. |
1331 |
> |
* Spin-waits up to the specified number of milliseconds for the given |
1332 |
> |
* thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING, |
1333 |
> |
* and additionally satisfy the given condition. |
1334 |
> |
*/ |
1335 |
> |
void waitForThreadToEnterWaitState( |
1336 |
> |
Thread thread, long timeoutMillis, Callable<Boolean> waitingForGodot) { |
1337 |
> |
long startTime = 0L; |
1338 |
> |
for (;;) { |
1339 |
> |
Thread.State s = thread.getState(); |
1340 |
> |
if (s == Thread.State.BLOCKED || |
1341 |
> |
s == Thread.State.WAITING || |
1342 |
> |
s == Thread.State.TIMED_WAITING) { |
1343 |
> |
try { |
1344 |
> |
if (waitingForGodot.call()) |
1345 |
> |
return; |
1346 |
> |
} catch (Throwable fail) { threadUnexpectedException(fail); } |
1347 |
> |
} |
1348 |
> |
else if (s == Thread.State.TERMINATED) |
1349 |
> |
fail("Unexpected thread termination"); |
1350 |
> |
else if (startTime == 0L) |
1351 |
> |
startTime = System.nanoTime(); |
1352 |
> |
else if (millisElapsedSince(startTime) > timeoutMillis) { |
1353 |
> |
threadAssertTrue(thread.isAlive()); |
1354 |
> |
fail("timed out waiting for thread to enter wait state"); |
1355 |
> |
} |
1356 |
> |
Thread.yield(); |
1357 |
> |
} |
1358 |
> |
} |
1359 |
> |
|
1360 |
> |
/** |
1361 |
> |
* Spin-waits up to LONG_DELAY_MS milliseconds for the given thread to |
1362 |
> |
* enter a wait state: BLOCKED, WAITING, or TIMED_WAITING. |
1363 |
|
*/ |
1364 |
|
void waitForThreadToEnterWaitState(Thread thread) { |
1365 |
|
waitForThreadToEnterWaitState(thread, LONG_DELAY_MS); |
1366 |
|
} |
1367 |
|
|
1368 |
|
/** |
1369 |
+ |
* Spin-waits up to LONG_DELAY_MS milliseconds for the given thread to |
1370 |
+ |
* enter a wait state: BLOCKED, WAITING, or TIMED_WAITING, |
1371 |
+ |
* and additionally satisfy the given condition. |
1372 |
+ |
*/ |
1373 |
+ |
void waitForThreadToEnterWaitState( |
1374 |
+ |
Thread thread, Callable<Boolean> waitingForGodot) { |
1375 |
+ |
waitForThreadToEnterWaitState(thread, LONG_DELAY_MS, waitingForGodot); |
1376 |
+ |
} |
1377 |
+ |
|
1378 |
+ |
/** |
1379 |
|
* Returns the number of milliseconds since time given by |
1380 |
|
* startNanoTime, which must have been previously returned from a |
1381 |
|
* call to {@link System#nanoTime()}. |
1437 |
|
} finally { |
1438 |
|
if (t.getState() != Thread.State.TERMINATED) { |
1439 |
|
t.interrupt(); |
1440 |
< |
fail("Test timed out"); |
1440 |
> |
threadFail("timed out waiting for thread to terminate"); |
1441 |
|
} |
1442 |
|
} |
1443 |
|
} |
1585 |
|
}}; |
1586 |
|
} |
1587 |
|
|
1588 |
< |
public Runnable awaiter(final CountDownLatch latch) { |
1589 |
< |
return new CheckedRunnable() { |
1590 |
< |
public void realRun() throws InterruptedException { |
1591 |
< |
await(latch); |
1592 |
< |
}}; |
1588 |
> |
class LatchAwaiter extends CheckedRunnable { |
1589 |
> |
static final int NEW = 0; |
1590 |
> |
static final int RUNNING = 1; |
1591 |
> |
static final int DONE = 2; |
1592 |
> |
final CountDownLatch latch; |
1593 |
> |
int state = NEW; |
1594 |
> |
LatchAwaiter(CountDownLatch latch) { this.latch = latch; } |
1595 |
> |
public void realRun() throws InterruptedException { |
1596 |
> |
state = 1; |
1597 |
> |
await(latch); |
1598 |
> |
state = 2; |
1599 |
> |
} |
1600 |
|
} |
1601 |
|
|
1602 |
< |
public void await(CountDownLatch latch) { |
1602 |
> |
public LatchAwaiter awaiter(CountDownLatch latch) { |
1603 |
> |
return new LatchAwaiter(latch); |
1604 |
> |
} |
1605 |
> |
|
1606 |
> |
public void await(CountDownLatch latch, long timeoutMillis) { |
1607 |
|
try { |
1608 |
< |
assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS)); |
1608 |
> |
if (!latch.await(timeoutMillis, MILLISECONDS)) |
1609 |
> |
fail("timed out waiting for CountDownLatch for " |
1610 |
> |
+ (timeoutMillis/1000) + " sec"); |
1611 |
|
} catch (Throwable fail) { |
1612 |
|
threadUnexpectedException(fail); |
1613 |
|
} |
1614 |
|
} |
1615 |
|
|
1616 |
+ |
public void await(CountDownLatch latch) { |
1617 |
+ |
await(latch, LONG_DELAY_MS); |
1618 |
+ |
} |
1619 |
+ |
|
1620 |
|
public void await(Semaphore semaphore) { |
1621 |
|
try { |
1622 |
< |
assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS)); |
1622 |
> |
if (!semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS)) |
1623 |
> |
fail("timed out waiting for Semaphore for " |
1624 |
> |
+ (LONG_DELAY_MS/1000) + " sec"); |
1625 |
> |
} catch (Throwable fail) { |
1626 |
> |
threadUnexpectedException(fail); |
1627 |
> |
} |
1628 |
> |
} |
1629 |
> |
|
1630 |
> |
public void await(CyclicBarrier barrier) { |
1631 |
> |
try { |
1632 |
> |
barrier.await(LONG_DELAY_MS, MILLISECONDS); |
1633 |
|
} catch (Throwable fail) { |
1634 |
|
threadUnexpectedException(fail); |
1635 |
|
} |
1658 |
|
public String call() { throw new NullPointerException(); } |
1659 |
|
} |
1660 |
|
|
1310 |
– |
public static class CallableOne implements Callable<Integer> { |
1311 |
– |
public Integer call() { return one; } |
1312 |
– |
} |
1313 |
– |
|
1314 |
– |
public class ShortRunnable extends CheckedRunnable { |
1315 |
– |
protected void realRun() throws Throwable { |
1316 |
– |
delay(SHORT_DELAY_MS); |
1317 |
– |
} |
1318 |
– |
} |
1319 |
– |
|
1320 |
– |
public class ShortInterruptedRunnable extends CheckedInterruptedRunnable { |
1321 |
– |
protected void realRun() throws InterruptedException { |
1322 |
– |
delay(SHORT_DELAY_MS); |
1323 |
– |
} |
1324 |
– |
} |
1325 |
– |
|
1326 |
– |
public class SmallRunnable extends CheckedRunnable { |
1327 |
– |
protected void realRun() throws Throwable { |
1328 |
– |
delay(SMALL_DELAY_MS); |
1329 |
– |
} |
1330 |
– |
} |
1331 |
– |
|
1661 |
|
public class SmallPossiblyInterruptedRunnable extends CheckedRunnable { |
1662 |
|
protected void realRun() { |
1663 |
|
try { |
1666 |
|
} |
1667 |
|
} |
1668 |
|
|
1340 |
– |
public class SmallCallable extends CheckedCallable { |
1341 |
– |
protected Object realCall() throws InterruptedException { |
1342 |
– |
delay(SMALL_DELAY_MS); |
1343 |
– |
return Boolean.TRUE; |
1344 |
– |
} |
1345 |
– |
} |
1346 |
– |
|
1347 |
– |
public class MediumRunnable extends CheckedRunnable { |
1348 |
– |
protected void realRun() throws Throwable { |
1349 |
– |
delay(MEDIUM_DELAY_MS); |
1350 |
– |
} |
1351 |
– |
} |
1352 |
– |
|
1353 |
– |
public class MediumInterruptedRunnable extends CheckedInterruptedRunnable { |
1354 |
– |
protected void realRun() throws InterruptedException { |
1355 |
– |
delay(MEDIUM_DELAY_MS); |
1356 |
– |
} |
1357 |
– |
} |
1358 |
– |
|
1669 |
|
public Runnable possiblyInterruptedRunnable(final long timeoutMillis) { |
1670 |
|
return new CheckedRunnable() { |
1671 |
|
protected void realRun() { |
1675 |
|
}}; |
1676 |
|
} |
1677 |
|
|
1368 |
– |
public class MediumPossiblyInterruptedRunnable extends CheckedRunnable { |
1369 |
– |
protected void realRun() { |
1370 |
– |
try { |
1371 |
– |
delay(MEDIUM_DELAY_MS); |
1372 |
– |
} catch (InterruptedException ok) {} |
1373 |
– |
} |
1374 |
– |
} |
1375 |
– |
|
1376 |
– |
public class LongPossiblyInterruptedRunnable extends CheckedRunnable { |
1377 |
– |
protected void realRun() { |
1378 |
– |
try { |
1379 |
– |
delay(LONG_DELAY_MS); |
1380 |
– |
} catch (InterruptedException ok) {} |
1381 |
– |
} |
1382 |
– |
} |
1383 |
– |
|
1678 |
|
/** |
1679 |
|
* For use as ThreadFactory in constructors |
1680 |
|
*/ |
1688 |
|
boolean isDone(); |
1689 |
|
} |
1690 |
|
|
1397 |
– |
public static TrackedRunnable trackedRunnable(final long timeoutMillis) { |
1398 |
– |
return new TrackedRunnable() { |
1399 |
– |
private volatile boolean done = false; |
1400 |
– |
public boolean isDone() { return done; } |
1401 |
– |
public void run() { |
1402 |
– |
try { |
1403 |
– |
delay(timeoutMillis); |
1404 |
– |
done = true; |
1405 |
– |
} catch (InterruptedException ok) {} |
1406 |
– |
} |
1407 |
– |
}; |
1408 |
– |
} |
1409 |
– |
|
1410 |
– |
public static class TrackedShortRunnable implements Runnable { |
1411 |
– |
public volatile boolean done = false; |
1412 |
– |
public void run() { |
1413 |
– |
try { |
1414 |
– |
delay(SHORT_DELAY_MS); |
1415 |
– |
done = true; |
1416 |
– |
} catch (InterruptedException ok) {} |
1417 |
– |
} |
1418 |
– |
} |
1419 |
– |
|
1420 |
– |
public static class TrackedSmallRunnable implements Runnable { |
1421 |
– |
public volatile boolean done = false; |
1422 |
– |
public void run() { |
1423 |
– |
try { |
1424 |
– |
delay(SMALL_DELAY_MS); |
1425 |
– |
done = true; |
1426 |
– |
} catch (InterruptedException ok) {} |
1427 |
– |
} |
1428 |
– |
} |
1429 |
– |
|
1430 |
– |
public static class TrackedMediumRunnable implements Runnable { |
1431 |
– |
public volatile boolean done = false; |
1432 |
– |
public void run() { |
1433 |
– |
try { |
1434 |
– |
delay(MEDIUM_DELAY_MS); |
1435 |
– |
done = true; |
1436 |
– |
} catch (InterruptedException ok) {} |
1437 |
– |
} |
1438 |
– |
} |
1439 |
– |
|
1440 |
– |
public static class TrackedLongRunnable implements Runnable { |
1441 |
– |
public volatile boolean done = false; |
1442 |
– |
public void run() { |
1443 |
– |
try { |
1444 |
– |
delay(LONG_DELAY_MS); |
1445 |
– |
done = true; |
1446 |
– |
} catch (InterruptedException ok) {} |
1447 |
– |
} |
1448 |
– |
} |
1449 |
– |
|
1691 |
|
public static class TrackedNoOpRunnable implements Runnable { |
1692 |
|
public volatile boolean done = false; |
1693 |
|
public void run() { |
1695 |
|
} |
1696 |
|
} |
1697 |
|
|
1457 |
– |
public static class TrackedCallable implements Callable { |
1458 |
– |
public volatile boolean done = false; |
1459 |
– |
public Object call() { |
1460 |
– |
try { |
1461 |
– |
delay(SMALL_DELAY_MS); |
1462 |
– |
done = true; |
1463 |
– |
} catch (InterruptedException ok) {} |
1464 |
– |
return Boolean.TRUE; |
1465 |
– |
} |
1466 |
– |
} |
1467 |
– |
|
1698 |
|
/** |
1699 |
|
* Analog of CheckedRunnable for RecursiveAction |
1700 |
|
*/ |
1738 |
|
* A CyclicBarrier that uses timed await and fails with |
1739 |
|
* AssertionFailedErrors instead of throwing checked exceptions. |
1740 |
|
*/ |
1741 |
< |
public class CheckedBarrier extends CyclicBarrier { |
1741 |
> |
public static class CheckedBarrier extends CyclicBarrier { |
1742 |
|
public CheckedBarrier(int parties) { super(parties); } |
1743 |
|
|
1744 |
|
public int await() { |
1761 |
|
assertEquals(0, q.size()); |
1762 |
|
assertNull(q.peek()); |
1763 |
|
assertNull(q.poll()); |
1764 |
< |
assertNull(q.poll(0, MILLISECONDS)); |
1764 |
> |
assertNull(q.poll(randomExpiredTimeout(), randomTimeUnit())); |
1765 |
|
assertEquals(q.toString(), "[]"); |
1766 |
|
assertTrue(Arrays.equals(q.toArray(), new Object[0])); |
1767 |
|
assertFalse(q.iterator().hasNext()); |
1802 |
|
} |
1803 |
|
} |
1804 |
|
|
1805 |
+ |
void assertImmutable(final Object o) { |
1806 |
+ |
if (o instanceof Collection) { |
1807 |
+ |
assertThrows( |
1808 |
+ |
UnsupportedOperationException.class, |
1809 |
+ |
new Runnable() { public void run() { |
1810 |
+ |
((Collection) o).add(null);}}); |
1811 |
+ |
} |
1812 |
+ |
} |
1813 |
+ |
|
1814 |
|
@SuppressWarnings("unchecked") |
1815 |
|
<T> T serialClone(T o) { |
1816 |
|
try { |
1817 |
|
ObjectInputStream ois = new ObjectInputStream |
1818 |
|
(new ByteArrayInputStream(serialBytes(o))); |
1819 |
|
T clone = (T) ois.readObject(); |
1820 |
+ |
if (o == clone) assertImmutable(o); |
1821 |
|
assertSame(o.getClass(), clone.getClass()); |
1822 |
|
return clone; |
1823 |
|
} catch (Throwable fail) { |
1826 |
|
} |
1827 |
|
} |
1828 |
|
|
1829 |
+ |
/** |
1830 |
+ |
* A version of serialClone that leaves error handling (for |
1831 |
+ |
* e.g. NotSerializableException) up to the caller. |
1832 |
+ |
*/ |
1833 |
+ |
@SuppressWarnings("unchecked") |
1834 |
+ |
<T> T serialClonePossiblyFailing(T o) |
1835 |
+ |
throws ReflectiveOperationException, java.io.IOException { |
1836 |
+ |
ByteArrayOutputStream bos = new ByteArrayOutputStream(); |
1837 |
+ |
ObjectOutputStream oos = new ObjectOutputStream(bos); |
1838 |
+ |
oos.writeObject(o); |
1839 |
+ |
oos.flush(); |
1840 |
+ |
oos.close(); |
1841 |
+ |
ObjectInputStream ois = new ObjectInputStream |
1842 |
+ |
(new ByteArrayInputStream(bos.toByteArray())); |
1843 |
+ |
T clone = (T) ois.readObject(); |
1844 |
+ |
if (o == clone) assertImmutable(o); |
1845 |
+ |
assertSame(o.getClass(), clone.getClass()); |
1846 |
+ |
return clone; |
1847 |
+ |
} |
1848 |
+ |
|
1849 |
+ |
/** |
1850 |
+ |
* If o implements Cloneable and has a public clone method, |
1851 |
+ |
* returns a clone of o, else null. |
1852 |
+ |
*/ |
1853 |
+ |
@SuppressWarnings("unchecked") |
1854 |
+ |
<T> T cloneableClone(T o) { |
1855 |
+ |
if (!(o instanceof Cloneable)) return null; |
1856 |
+ |
final T clone; |
1857 |
+ |
try { |
1858 |
+ |
clone = (T) o.getClass().getMethod("clone").invoke(o); |
1859 |
+ |
} catch (NoSuchMethodException ok) { |
1860 |
+ |
return null; |
1861 |
+ |
} catch (ReflectiveOperationException unexpected) { |
1862 |
+ |
throw new Error(unexpected); |
1863 |
+ |
} |
1864 |
+ |
assertNotSame(o, clone); // not 100% guaranteed by spec |
1865 |
+ |
assertSame(o.getClass(), clone.getClass()); |
1866 |
+ |
return clone; |
1867 |
+ |
} |
1868 |
+ |
|
1869 |
|
public void assertThrows(Class<? extends Throwable> expectedExceptionClass, |
1870 |
|
Runnable... throwingActions) { |
1871 |
|
for (Runnable throwingAction : throwingActions) { |
1894 |
|
} catch (NoSuchElementException success) {} |
1895 |
|
assertFalse(it.hasNext()); |
1896 |
|
} |
1897 |
+ |
|
1898 |
+ |
public <T> Callable<T> callableThrowing(final Exception ex) { |
1899 |
+ |
return new Callable<T>() { public T call() throws Exception { throw ex; }}; |
1900 |
+ |
} |
1901 |
+ |
|
1902 |
+ |
public Runnable runnableThrowing(final RuntimeException ex) { |
1903 |
+ |
return new Runnable() { public void run() { throw ex; }}; |
1904 |
+ |
} |
1905 |
+ |
|
1906 |
+ |
/** A reusable thread pool to be shared by tests. */ |
1907 |
+ |
static final ExecutorService cachedThreadPool = |
1908 |
+ |
new ThreadPoolExecutor(0, Integer.MAX_VALUE, |
1909 |
+ |
1000L, MILLISECONDS, |
1910 |
+ |
new SynchronousQueue<Runnable>()); |
1911 |
+ |
|
1912 |
+ |
static <T> void shuffle(T[] array) { |
1913 |
+ |
Collections.shuffle(Arrays.asList(array), ThreadLocalRandom.current()); |
1914 |
+ |
} |
1915 |
+ |
|
1916 |
+ |
// --- Shared assertions for Executor tests --- |
1917 |
+ |
|
1918 |
+ |
/** |
1919 |
+ |
* Returns maximum number of tasks that can be submitted to given |
1920 |
+ |
* pool (with bounded queue) before saturation (when submission |
1921 |
+ |
* throws RejectedExecutionException). |
1922 |
+ |
*/ |
1923 |
+ |
static final int saturatedSize(ThreadPoolExecutor pool) { |
1924 |
+ |
BlockingQueue<Runnable> q = pool.getQueue(); |
1925 |
+ |
return pool.getMaximumPoolSize() + q.size() + q.remainingCapacity(); |
1926 |
+ |
} |
1927 |
+ |
|
1928 |
+ |
@SuppressWarnings("FutureReturnValueIgnored") |
1929 |
+ |
void assertNullTaskSubmissionThrowsNullPointerException(Executor e) { |
1930 |
+ |
try { |
1931 |
+ |
e.execute((Runnable) null); |
1932 |
+ |
shouldThrow(); |
1933 |
+ |
} catch (NullPointerException success) {} |
1934 |
+ |
|
1935 |
+ |
if (! (e instanceof ExecutorService)) return; |
1936 |
+ |
ExecutorService es = (ExecutorService) e; |
1937 |
+ |
try { |
1938 |
+ |
es.submit((Runnable) null); |
1939 |
+ |
shouldThrow(); |
1940 |
+ |
} catch (NullPointerException success) {} |
1941 |
+ |
try { |
1942 |
+ |
es.submit((Runnable) null, Boolean.TRUE); |
1943 |
+ |
shouldThrow(); |
1944 |
+ |
} catch (NullPointerException success) {} |
1945 |
+ |
try { |
1946 |
+ |
es.submit((Callable) null); |
1947 |
+ |
shouldThrow(); |
1948 |
+ |
} catch (NullPointerException success) {} |
1949 |
+ |
|
1950 |
+ |
if (! (e instanceof ScheduledExecutorService)) return; |
1951 |
+ |
ScheduledExecutorService ses = (ScheduledExecutorService) e; |
1952 |
+ |
try { |
1953 |
+ |
ses.schedule((Runnable) null, |
1954 |
+ |
randomTimeout(), randomTimeUnit()); |
1955 |
+ |
shouldThrow(); |
1956 |
+ |
} catch (NullPointerException success) {} |
1957 |
+ |
try { |
1958 |
+ |
ses.schedule((Callable) null, |
1959 |
+ |
randomTimeout(), randomTimeUnit()); |
1960 |
+ |
shouldThrow(); |
1961 |
+ |
} catch (NullPointerException success) {} |
1962 |
+ |
try { |
1963 |
+ |
ses.scheduleAtFixedRate((Runnable) null, |
1964 |
+ |
randomTimeout(), LONG_DELAY_MS, MILLISECONDS); |
1965 |
+ |
shouldThrow(); |
1966 |
+ |
} catch (NullPointerException success) {} |
1967 |
+ |
try { |
1968 |
+ |
ses.scheduleWithFixedDelay((Runnable) null, |
1969 |
+ |
randomTimeout(), LONG_DELAY_MS, MILLISECONDS); |
1970 |
+ |
shouldThrow(); |
1971 |
+ |
} catch (NullPointerException success) {} |
1972 |
+ |
} |
1973 |
+ |
|
1974 |
+ |
void setRejectedExecutionHandler( |
1975 |
+ |
ThreadPoolExecutor p, RejectedExecutionHandler handler) { |
1976 |
+ |
p.setRejectedExecutionHandler(handler); |
1977 |
+ |
assertSame(handler, p.getRejectedExecutionHandler()); |
1978 |
+ |
} |
1979 |
+ |
|
1980 |
+ |
void assertTaskSubmissionsAreRejected(ThreadPoolExecutor p) { |
1981 |
+ |
final RejectedExecutionHandler savedHandler = p.getRejectedExecutionHandler(); |
1982 |
+ |
final long savedTaskCount = p.getTaskCount(); |
1983 |
+ |
final long savedCompletedTaskCount = p.getCompletedTaskCount(); |
1984 |
+ |
final int savedQueueSize = p.getQueue().size(); |
1985 |
+ |
final boolean stock = (p.getClass().getClassLoader() == null); |
1986 |
+ |
|
1987 |
+ |
Runnable r = () -> {}; |
1988 |
+ |
Callable<Boolean> c = () -> Boolean.TRUE; |
1989 |
+ |
|
1990 |
+ |
class Recorder implements RejectedExecutionHandler { |
1991 |
+ |
public volatile Runnable r = null; |
1992 |
+ |
public volatile ThreadPoolExecutor p = null; |
1993 |
+ |
public void reset() { r = null; p = null; } |
1994 |
+ |
public void rejectedExecution(Runnable r, ThreadPoolExecutor p) { |
1995 |
+ |
assertNull(this.r); |
1996 |
+ |
assertNull(this.p); |
1997 |
+ |
this.r = r; |
1998 |
+ |
this.p = p; |
1999 |
+ |
} |
2000 |
+ |
} |
2001 |
+ |
|
2002 |
+ |
// check custom handler is invoked exactly once per task |
2003 |
+ |
Recorder recorder = new Recorder(); |
2004 |
+ |
setRejectedExecutionHandler(p, recorder); |
2005 |
+ |
for (int i = 2; i--> 0; ) { |
2006 |
+ |
recorder.reset(); |
2007 |
+ |
p.execute(r); |
2008 |
+ |
if (stock && p.getClass() == ThreadPoolExecutor.class) |
2009 |
+ |
assertSame(r, recorder.r); |
2010 |
+ |
assertSame(p, recorder.p); |
2011 |
+ |
|
2012 |
+ |
recorder.reset(); |
2013 |
+ |
assertFalse(p.submit(r).isDone()); |
2014 |
+ |
if (stock) assertTrue(!((FutureTask) recorder.r).isDone()); |
2015 |
+ |
assertSame(p, recorder.p); |
2016 |
+ |
|
2017 |
+ |
recorder.reset(); |
2018 |
+ |
assertFalse(p.submit(r, Boolean.TRUE).isDone()); |
2019 |
+ |
if (stock) assertTrue(!((FutureTask) recorder.r).isDone()); |
2020 |
+ |
assertSame(p, recorder.p); |
2021 |
+ |
|
2022 |
+ |
recorder.reset(); |
2023 |
+ |
assertFalse(p.submit(c).isDone()); |
2024 |
+ |
if (stock) assertTrue(!((FutureTask) recorder.r).isDone()); |
2025 |
+ |
assertSame(p, recorder.p); |
2026 |
+ |
|
2027 |
+ |
if (p instanceof ScheduledExecutorService) { |
2028 |
+ |
ScheduledExecutorService s = (ScheduledExecutorService) p; |
2029 |
+ |
ScheduledFuture<?> future; |
2030 |
+ |
|
2031 |
+ |
recorder.reset(); |
2032 |
+ |
future = s.schedule(r, randomTimeout(), randomTimeUnit()); |
2033 |
+ |
assertFalse(future.isDone()); |
2034 |
+ |
if (stock) assertTrue(!((FutureTask) recorder.r).isDone()); |
2035 |
+ |
assertSame(p, recorder.p); |
2036 |
+ |
|
2037 |
+ |
recorder.reset(); |
2038 |
+ |
future = s.schedule(c, randomTimeout(), randomTimeUnit()); |
2039 |
+ |
assertFalse(future.isDone()); |
2040 |
+ |
if (stock) assertTrue(!((FutureTask) recorder.r).isDone()); |
2041 |
+ |
assertSame(p, recorder.p); |
2042 |
+ |
|
2043 |
+ |
recorder.reset(); |
2044 |
+ |
future = s.scheduleAtFixedRate(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS); |
2045 |
+ |
assertFalse(future.isDone()); |
2046 |
+ |
if (stock) assertTrue(!((FutureTask) recorder.r).isDone()); |
2047 |
+ |
assertSame(p, recorder.p); |
2048 |
+ |
|
2049 |
+ |
recorder.reset(); |
2050 |
+ |
future = s.scheduleWithFixedDelay(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS); |
2051 |
+ |
assertFalse(future.isDone()); |
2052 |
+ |
if (stock) assertTrue(!((FutureTask) recorder.r).isDone()); |
2053 |
+ |
assertSame(p, recorder.p); |
2054 |
+ |
} |
2055 |
+ |
} |
2056 |
+ |
|
2057 |
+ |
// Checking our custom handler above should be sufficient, but |
2058 |
+ |
// we add some integration tests of standard handlers. |
2059 |
+ |
final AtomicReference<Thread> thread = new AtomicReference<>(); |
2060 |
+ |
final Runnable setThread = () -> thread.set(Thread.currentThread()); |
2061 |
+ |
|
2062 |
+ |
setRejectedExecutionHandler(p, new ThreadPoolExecutor.AbortPolicy()); |
2063 |
+ |
try { |
2064 |
+ |
p.execute(setThread); |
2065 |
+ |
shouldThrow(); |
2066 |
+ |
} catch (RejectedExecutionException success) {} |
2067 |
+ |
assertNull(thread.get()); |
2068 |
+ |
|
2069 |
+ |
setRejectedExecutionHandler(p, new ThreadPoolExecutor.DiscardPolicy()); |
2070 |
+ |
p.execute(setThread); |
2071 |
+ |
assertNull(thread.get()); |
2072 |
+ |
|
2073 |
+ |
setRejectedExecutionHandler(p, new ThreadPoolExecutor.CallerRunsPolicy()); |
2074 |
+ |
p.execute(setThread); |
2075 |
+ |
if (p.isShutdown()) |
2076 |
+ |
assertNull(thread.get()); |
2077 |
+ |
else |
2078 |
+ |
assertSame(Thread.currentThread(), thread.get()); |
2079 |
+ |
|
2080 |
+ |
setRejectedExecutionHandler(p, savedHandler); |
2081 |
+ |
|
2082 |
+ |
// check that pool was not perturbed by handlers |
2083 |
+ |
assertEquals(savedTaskCount, p.getTaskCount()); |
2084 |
+ |
assertEquals(savedCompletedTaskCount, p.getCompletedTaskCount()); |
2085 |
+ |
assertEquals(savedQueueSize, p.getQueue().size()); |
2086 |
+ |
} |
2087 |
|
} |