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; |
57 |
|
import java.security.CodeSource; |
58 |
|
import java.security.Permission; |
59 |
|
import java.security.PermissionCollection; |
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; |
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.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 |
|
|
115 |
|
* |
116 |
|
* <ol> |
117 |
|
* |
118 |
< |
* <li> All assertions in code running in generated threads must use |
118 |
> |
* <li>All assertions in code running in generated threads must use |
119 |
|
* the forms {@link #threadFail}, {@link #threadAssertTrue}, {@link |
120 |
|
* #threadAssertEquals}, or {@link #threadAssertNull}, (not |
121 |
|
* {@code fail}, {@code assertTrue}, etc.) It is OK (but not |
122 |
|
* particularly recommended) for other code to use these forms too. |
123 |
|
* Only the most typically used JUnit assertion methods are defined |
124 |
< |
* this way, but enough to live with.</li> |
124 |
> |
* this way, but enough to live with. |
125 |
|
* |
126 |
< |
* <li> If you override {@link #setUp} or {@link #tearDown}, make sure |
126 |
> |
* <li>If you override {@link #setUp} or {@link #tearDown}, make sure |
127 |
|
* to invoke {@code super.setUp} and {@code super.tearDown} within |
128 |
|
* them. These methods are used to clear and check for thread |
129 |
< |
* assertion failures.</li> |
129 |
> |
* assertion failures. |
130 |
|
* |
131 |
|
* <li>All delays and timeouts must use one of the constants {@code |
132 |
|
* SHORT_DELAY_MS}, {@code SMALL_DELAY_MS}, {@code MEDIUM_DELAY_MS}, |
137 |
|
* is always discriminable as larger than SHORT and smaller than |
138 |
|
* MEDIUM. And so on. These constants are set to conservative values, |
139 |
|
* but even so, if there is ever any doubt, they can all be increased |
140 |
< |
* in one spot to rerun tests on slower platforms.</li> |
140 |
> |
* in one spot to rerun tests on slower platforms. |
141 |
|
* |
142 |
< |
* <li> All threads generated must be joined inside each test case |
142 |
> |
* <li>All threads generated must be joined inside each test case |
143 |
|
* method (or {@code fail} to do so) before returning from the |
144 |
|
* method. The {@code joinPool} method can be used to do this when |
145 |
< |
* using Executors.</li> |
145 |
> |
* using Executors. |
146 |
|
* |
147 |
|
* </ol> |
148 |
|
* |
149 |
|
* <p><b>Other notes</b> |
150 |
|
* <ul> |
151 |
|
* |
152 |
< |
* <li> Usually, there is one testcase method per JSR166 method |
152 |
> |
* <li>Usually, there is one testcase method per JSR166 method |
153 |
|
* covering "normal" operation, and then as many exception-testing |
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 |
106 |
< |
* isolation.</li> |
157 |
> |
* cover multiple methods when they cannot be tested in isolation. |
158 |
|
* |
159 |
< |
* <li> The documentation style for testcases is to provide as javadoc |
159 |
> |
* <li>The documentation style for testcases is to provide as javadoc |
160 |
|
* a simple sentence or two describing the property that the testcase |
161 |
|
* method purports to test. The javadocs do not say anything about how |
162 |
< |
* the property is tested. To find out, read the code.</li> |
162 |
> |
* the property is tested. To find out, read the code. |
163 |
|
* |
164 |
< |
* <li> These tests are "conformance tests", and do not attempt to |
164 |
> |
* <li>These tests are "conformance tests", and do not attempt to |
165 |
|
* test throughput, latency, scalability or other performance factors |
166 |
|
* (see the separate "jtreg" tests for a set intended to check these |
167 |
|
* for the most central aspects of functionality.) So, most tests use |
168 |
|
* the smallest sensible numbers of threads, collection sizes, etc |
169 |
< |
* needed to check basic conformance.</li> |
169 |
> |
* needed to check basic conformance. |
170 |
|
* |
171 |
|
* <li>The test classes currently do not declare inclusion in |
172 |
|
* any particular package to simplify things for people integrating |
173 |
< |
* them in TCK test suites.</li> |
173 |
> |
* them in TCK test suites. |
174 |
|
* |
175 |
< |
* <li> As a convenience, the {@code main} of this class (JSR166TestCase) |
176 |
< |
* runs all JSR166 unit tests.</li> |
175 |
> |
* <li>As a convenience, the {@code main} of this class (JSR166TestCase) |
176 |
> |
* runs all JSR166 unit tests. |
177 |
|
* |
178 |
|
* </ul> |
179 |
|
*/ |
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 |
+ |
|
261 |
+ |
/** |
262 |
|
* A filter for tests to run, matching strings of the form |
263 |
|
* methodName(className), e.g. "testInvokeAll5(ForkJoinPoolTest)" |
264 |
|
* Usefully combined with jsr166.runsPerTest. |
270 |
|
return (regex == null) ? null : Pattern.compile(regex); |
271 |
|
} |
272 |
|
|
273 |
< |
protected void runTest() throws Throwable { |
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 |
< |
for (int i = 0; i < runsPerTest; i++) { |
324 |
< |
if (profileTests) |
325 |
< |
runTestProfiled(); |
326 |
< |
else |
327 |
< |
super.runTest(); |
328 |
< |
} |
322 |
> |
|| methodFilter.matcher(toString()).find()) |
323 |
> |
super.runBare(); |
324 |
> |
} |
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 |
332 |
> |
super.runTest(); |
333 |
|
} |
334 |
|
} |
335 |
|
|
336 |
|
protected void runTestProfiled() throws Throwable { |
337 |
< |
// Warmup run, notably to trigger all needed classloading. |
338 |
< |
super.runTest(); |
196 |
< |
long t0 = System.nanoTime(); |
197 |
< |
try { |
337 |
> |
for (int i = 0; i < 2; i++) { |
338 |
> |
long startTime = System.nanoTime(); |
339 |
|
super.runTest(); |
340 |
< |
} finally { |
341 |
< |
long elapsedMillis = millisElapsedSince(t0); |
342 |
< |
if (elapsedMillis >= profileThreshold) |
340 |
> |
long elapsedMillis = millisElapsedSince(startTime); |
341 |
> |
if (elapsedMillis < profileThreshold) |
342 |
> |
break; |
343 |
> |
// Never report first run of any test; treat it as a |
344 |
> |
// warmup run, notably to trigger all needed classloading, |
345 |
> |
if (i > 0) |
346 |
|
System.out.printf("%n%s: %d%n", toString(), elapsedMillis); |
347 |
|
} |
348 |
|
} |
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(); |
445 |
|
} |
446 |
|
} |
447 |
|
|
448 |
< |
public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; } |
449 |
< |
public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; } |
450 |
< |
public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; } |
451 |
< |
public static boolean atLeastJava9() { return JAVA_CLASS_VERSION >= 53.0; } |
448 |
> |
public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; } |
449 |
> |
public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; } |
450 |
> |
public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; } |
451 |
> |
public static boolean atLeastJava9() { return JAVA_CLASS_VERSION >= 53.0; } |
452 |
> |
public static boolean atLeastJava10() { return JAVA_CLASS_VERSION >= 54.0; } |
453 |
|
|
454 |
|
/** |
455 |
|
* Collects all JSR166 unit tests as one suite. |
470 |
|
AbstractQueuedLongSynchronizerTest.suite(), |
471 |
|
ArrayBlockingQueueTest.suite(), |
472 |
|
ArrayDequeTest.suite(), |
473 |
+ |
ArrayListTest.suite(), |
474 |
|
AtomicBooleanTest.suite(), |
475 |
|
AtomicIntegerArrayTest.suite(), |
476 |
|
AtomicIntegerFieldUpdaterTest.suite(), |
493 |
|
CopyOnWriteArrayListTest.suite(), |
494 |
|
CopyOnWriteArraySetTest.suite(), |
495 |
|
CountDownLatchTest.suite(), |
496 |
+ |
CountedCompleterTest.suite(), |
497 |
|
CyclicBarrierTest.suite(), |
498 |
|
DelayQueueTest.suite(), |
499 |
|
EntryTest.suite(), |
522 |
|
TreeMapTest.suite(), |
523 |
|
TreeSetTest.suite(), |
524 |
|
TreeSubMapTest.suite(), |
525 |
< |
TreeSubSetTest.suite()); |
525 |
> |
TreeSubSetTest.suite(), |
526 |
> |
VectorTest.suite()); |
527 |
|
|
528 |
|
// Java8+ test classes |
529 |
|
if (atLeastJava8()) { |
530 |
|
String[] java8TestClassNames = { |
531 |
+ |
"ArrayDeque8Test", |
532 |
|
"Atomic8Test", |
533 |
|
"CompletableFutureTest", |
534 |
|
"ConcurrentHashMap8Test", |
535 |
< |
"CountedCompleterTest", |
535 |
> |
"CountedCompleter8Test", |
536 |
|
"DoubleAccumulatorTest", |
537 |
|
"DoubleAdderTest", |
538 |
|
"ForkJoinPool8Test", |
539 |
|
"ForkJoinTask8Test", |
540 |
+ |
"HashMapTest", |
541 |
+ |
"LinkedBlockingDeque8Test", |
542 |
+ |
"LinkedBlockingQueue8Test", |
543 |
|
"LongAccumulatorTest", |
544 |
|
"LongAdderTest", |
545 |
|
"SplittableRandomTest", |
546 |
|
"StampedLockTest", |
547 |
+ |
"SubmissionPublisherTest", |
548 |
|
"ThreadLocalRandom8Test", |
549 |
+ |
"TimeUnit8Test", |
550 |
|
}; |
551 |
|
addNamedTestClasses(suite, java8TestClassNames); |
552 |
|
} |
554 |
|
// Java9+ test classes |
555 |
|
if (atLeastJava9()) { |
556 |
|
String[] java9TestClassNames = { |
557 |
< |
"ThreadPoolExecutor9Test", |
557 |
> |
"AtomicBoolean9Test", |
558 |
> |
"AtomicInteger9Test", |
559 |
> |
"AtomicIntegerArray9Test", |
560 |
> |
"AtomicLong9Test", |
561 |
> |
"AtomicLongArray9Test", |
562 |
> |
"AtomicReference9Test", |
563 |
> |
"AtomicReferenceArray9Test", |
564 |
> |
"ExecutorCompletionService9Test", |
565 |
> |
"ForkJoinPool9Test", |
566 |
|
}; |
567 |
|
addNamedTestClasses(suite, java9TestClassNames); |
568 |
|
} |
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; |
638 |
|
public static long MEDIUM_DELAY_MS; |
639 |
|
public static long LONG_DELAY_MS; |
640 |
|
|
641 |
+ |
private static final long RANDOM_TIMEOUT; |
642 |
+ |
private static final long RANDOM_EXPIRED_TIMEOUT; |
643 |
+ |
private static final TimeUnit RANDOM_TIMEUNIT; |
644 |
+ |
static { |
645 |
+ |
ThreadLocalRandom rnd = ThreadLocalRandom.current(); |
646 |
+ |
long[] timeouts = { Long.MIN_VALUE, -1, 0, 1, Long.MAX_VALUE }; |
647 |
+ |
RANDOM_TIMEOUT = timeouts[rnd.nextInt(timeouts.length)]; |
648 |
+ |
RANDOM_EXPIRED_TIMEOUT = timeouts[rnd.nextInt(3)]; |
649 |
+ |
TimeUnit[] timeUnits = TimeUnit.values(); |
650 |
+ |
RANDOM_TIMEUNIT = timeUnits[rnd.nextInt(timeUnits.length)]; |
651 |
+ |
} |
652 |
+ |
|
653 |
+ |
/** |
654 |
+ |
* Returns a timeout for use when any value at all will do. |
655 |
+ |
*/ |
656 |
+ |
static long randomTimeout() { return RANDOM_TIMEOUT; } |
657 |
+ |
|
658 |
|
/** |
659 |
< |
* Returns the shortest timed delay. This could |
660 |
< |
* be reimplemented to use for example a Property. |
659 |
> |
* Returns a timeout that means "no waiting", i.e. not positive. |
660 |
> |
*/ |
661 |
> |
static long randomExpiredTimeout() { return RANDOM_EXPIRED_TIMEOUT; } |
662 |
> |
|
663 |
> |
/** |
664 |
> |
* Returns a random non-null TimeUnit. |
665 |
> |
*/ |
666 |
> |
static TimeUnit randomTimeUnit() { return RANDOM_TIMEUNIT; } |
667 |
> |
|
668 |
> |
/** |
669 |
> |
* Returns the shortest timed delay. This can be scaled up for |
670 |
> |
* slow machines using the jsr166.delay.factor system property, |
671 |
> |
* or via jtreg's -timeoutFactor: flag. |
672 |
> |
* http://openjdk.java.net/jtreg/command-help.html |
673 |
|
*/ |
674 |
|
protected long getShortDelay() { |
675 |
< |
return 50; |
675 |
> |
return (long) (50 * delayFactor); |
676 |
|
} |
677 |
|
|
678 |
|
/** |
685 |
|
LONG_DELAY_MS = SHORT_DELAY_MS * 200; |
686 |
|
} |
687 |
|
|
688 |
+ |
private static final long TIMEOUT_DELAY_MS |
689 |
+ |
= (long) (12.0 * Math.cbrt(delayFactor)); |
690 |
+ |
|
691 |
|
/** |
692 |
< |
* Returns a timeout in milliseconds to be used in tests that |
693 |
< |
* verify that operations block or time out. |
692 |
> |
* Returns a timeout in milliseconds to be used in tests that verify |
693 |
> |
* that operations block or time out. We want this to be longer |
694 |
> |
* than the OS scheduling quantum, but not too long, so don't scale |
695 |
> |
* linearly with delayFactor; we use "crazy" cube root instead. |
696 |
|
*/ |
697 |
< |
long timeoutMillis() { |
698 |
< |
return SHORT_DELAY_MS / 4; |
697 |
> |
static long timeoutMillis() { |
698 |
> |
return TIMEOUT_DELAY_MS; |
699 |
|
} |
700 |
|
|
701 |
|
/** |
702 |
< |
* Returns a new Date instance representing a time delayMillis |
703 |
< |
* milliseconds in the future. |
702 |
> |
* Returns a new Date instance representing a time at least |
703 |
> |
* delayMillis milliseconds in the future. |
704 |
|
*/ |
705 |
|
Date delayedDate(long delayMillis) { |
706 |
< |
return new Date(System.currentTimeMillis() + delayMillis); |
706 |
> |
// Add 1 because currentTimeMillis is known to round into the past. |
707 |
> |
return new Date(System.currentTimeMillis() + delayMillis + 1); |
708 |
|
} |
709 |
|
|
710 |
|
/** |
711 |
|
* The first exception encountered if any threadAssertXXX method fails. |
712 |
|
*/ |
713 |
|
private final AtomicReference<Throwable> threadFailure |
714 |
< |
= new AtomicReference<Throwable>(null); |
714 |
> |
= new AtomicReference<>(null); |
715 |
|
|
716 |
|
/** |
717 |
|
* Records an exception so that it can be rethrown later in the test |
720 |
|
* the same test have no effect. |
721 |
|
*/ |
722 |
|
public void threadRecordFailure(Throwable t) { |
723 |
+ |
System.err.println(t); |
724 |
+ |
dumpTestThreads(); |
725 |
|
threadFailure.compareAndSet(null, t); |
726 |
|
} |
727 |
|
|
729 |
|
setDelays(); |
730 |
|
} |
731 |
|
|
732 |
+ |
void tearDownFail(String format, Object... args) { |
733 |
+ |
String msg = toString() + ": " + String.format(format, args); |
734 |
+ |
System.err.println(msg); |
735 |
+ |
dumpTestThreads(); |
736 |
+ |
throw new AssertionFailedError(msg); |
737 |
+ |
} |
738 |
+ |
|
739 |
|
/** |
740 |
|
* Extra checks that get done for all test cases. |
741 |
|
* |
763 |
|
} |
764 |
|
|
765 |
|
if (Thread.interrupted()) |
766 |
< |
throw new AssertionFailedError("interrupt status set in main thread"); |
766 |
> |
tearDownFail("interrupt status set in main thread"); |
767 |
|
|
768 |
|
checkForkJoinPoolThreadLeaks(); |
769 |
|
} |
770 |
|
|
771 |
|
/** |
772 |
< |
* Finds missing try { ... } finally { joinPool(e); } |
772 |
> |
* Finds missing PoolCleaners |
773 |
|
*/ |
774 |
|
void checkForkJoinPoolThreadLeaks() throws InterruptedException { |
775 |
< |
Thread[] survivors = new Thread[5]; |
775 |
> |
Thread[] survivors = new Thread[7]; |
776 |
|
int count = Thread.enumerate(survivors); |
777 |
|
for (int i = 0; i < count; i++) { |
778 |
|
Thread thread = survivors[i]; |
780 |
|
if (name.startsWith("ForkJoinPool-")) { |
781 |
|
// give thread some time to terminate |
782 |
|
thread.join(LONG_DELAY_MS); |
783 |
< |
if (!thread.isAlive()) continue; |
784 |
< |
throw new AssertionFailedError |
785 |
< |
(String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n", |
491 |
< |
toString(), name)); |
783 |
> |
if (thread.isAlive()) |
784 |
> |
tearDownFail("Found leaked ForkJoinPool thread thread=%s", |
785 |
> |
thread); |
786 |
|
} |
787 |
|
} |
788 |
+ |
|
789 |
+ |
if (!ForkJoinPool.commonPool() |
790 |
+ |
.awaitQuiescence(LONG_DELAY_MS, MILLISECONDS)) |
791 |
+ |
tearDownFail("ForkJoin common pool thread stuck"); |
792 |
|
} |
793 |
|
|
794 |
|
/** |
801 |
|
fail(reason); |
802 |
|
} catch (AssertionFailedError t) { |
803 |
|
threadRecordFailure(t); |
804 |
< |
fail(reason); |
804 |
> |
throw t; |
805 |
|
} |
806 |
|
} |
807 |
|
|
928 |
|
/** |
929 |
|
* Delays, via Thread.sleep, for the given millisecond delay, but |
930 |
|
* if the sleep is shorter than specified, may re-sleep or yield |
931 |
< |
* until time elapses. |
931 |
> |
* until time elapses. Ensures that the given time, as measured |
932 |
> |
* by System.nanoTime(), has elapsed. |
933 |
|
*/ |
934 |
|
static void delay(long millis) throws InterruptedException { |
935 |
< |
long startTime = System.nanoTime(); |
936 |
< |
long ns = millis * 1000 * 1000; |
937 |
< |
for (;;) { |
935 |
> |
long nanos = millis * (1000 * 1000); |
936 |
> |
final long wakeupTime = System.nanoTime() + nanos; |
937 |
> |
do { |
938 |
|
if (millis > 0L) |
939 |
|
Thread.sleep(millis); |
940 |
|
else // too short to sleep |
941 |
|
Thread.yield(); |
942 |
< |
long d = ns - (System.nanoTime() - startTime); |
943 |
< |
if (d > 0L) |
944 |
< |
millis = d / (1000 * 1000); |
945 |
< |
else |
946 |
< |
break; |
942 |
> |
nanos = wakeupTime - System.nanoTime(); |
943 |
> |
millis = nanos / (1000 * 1000); |
944 |
> |
} while (nanos >= 0L); |
945 |
> |
} |
946 |
> |
|
947 |
> |
/** |
948 |
> |
* Allows use of try-with-resources with per-test thread pools. |
949 |
> |
*/ |
950 |
> |
class PoolCleaner implements AutoCloseable { |
951 |
> |
private final ExecutorService pool; |
952 |
> |
public PoolCleaner(ExecutorService pool) { this.pool = pool; } |
953 |
> |
public void close() { joinPool(pool); } |
954 |
> |
} |
955 |
> |
|
956 |
> |
/** |
957 |
> |
* An extension of PoolCleaner that has an action to release the pool. |
958 |
> |
*/ |
959 |
> |
class PoolCleanerWithReleaser extends PoolCleaner { |
960 |
> |
private final Runnable releaser; |
961 |
> |
public PoolCleanerWithReleaser(ExecutorService pool, Runnable releaser) { |
962 |
> |
super(pool); |
963 |
> |
this.releaser = releaser; |
964 |
|
} |
965 |
+ |
public void close() { |
966 |
+ |
try { |
967 |
+ |
releaser.run(); |
968 |
+ |
} finally { |
969 |
+ |
super.close(); |
970 |
+ |
} |
971 |
+ |
} |
972 |
+ |
} |
973 |
+ |
|
974 |
+ |
PoolCleaner cleaner(ExecutorService pool) { |
975 |
+ |
return new PoolCleaner(pool); |
976 |
+ |
} |
977 |
+ |
|
978 |
+ |
PoolCleaner cleaner(ExecutorService pool, Runnable releaser) { |
979 |
+ |
return new PoolCleanerWithReleaser(pool, releaser); |
980 |
+ |
} |
981 |
+ |
|
982 |
+ |
PoolCleaner cleaner(ExecutorService pool, CountDownLatch latch) { |
983 |
+ |
return new PoolCleanerWithReleaser(pool, releaser(latch)); |
984 |
+ |
} |
985 |
+ |
|
986 |
+ |
Runnable releaser(final CountDownLatch latch) { |
987 |
+ |
return new Runnable() { public void run() { |
988 |
+ |
do { latch.countDown(); } |
989 |
+ |
while (latch.getCount() > 0); |
990 |
+ |
}}; |
991 |
+ |
} |
992 |
+ |
|
993 |
+ |
PoolCleaner cleaner(ExecutorService pool, AtomicBoolean flag) { |
994 |
+ |
return new PoolCleanerWithReleaser(pool, releaser(flag)); |
995 |
+ |
} |
996 |
+ |
|
997 |
+ |
Runnable releaser(final AtomicBoolean flag) { |
998 |
+ |
return new Runnable() { public void run() { flag.set(true); }}; |
999 |
|
} |
1000 |
|
|
1001 |
|
/** |
1002 |
|
* Waits out termination of a thread pool or fails doing so. |
1003 |
|
*/ |
1004 |
< |
void joinPool(ExecutorService exec) { |
1004 |
> |
void joinPool(ExecutorService pool) { |
1005 |
|
try { |
1006 |
< |
exec.shutdown(); |
1007 |
< |
if (!exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS)) |
1008 |
< |
fail("ExecutorService " + exec + |
1009 |
< |
" did not terminate in a timely manner"); |
1006 |
> |
pool.shutdown(); |
1007 |
> |
if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS)) { |
1008 |
> |
try { |
1009 |
> |
threadFail("ExecutorService " + pool + |
1010 |
> |
" did not terminate in a timely manner"); |
1011 |
> |
} finally { |
1012 |
> |
// last resort, for the benefit of subsequent tests |
1013 |
> |
pool.shutdownNow(); |
1014 |
> |
pool.awaitTermination(MEDIUM_DELAY_MS, MILLISECONDS); |
1015 |
> |
} |
1016 |
> |
} |
1017 |
|
} catch (SecurityException ok) { |
1018 |
|
// Allowed in case test doesn't have privs |
1019 |
|
} catch (InterruptedException fail) { |
1020 |
< |
fail("Unexpected InterruptedException"); |
1020 |
> |
threadFail("Unexpected InterruptedException"); |
1021 |
|
} |
1022 |
|
} |
1023 |
|
|
1024 |
|
/** |
1025 |
< |
* A debugging tool to print all stack traces, as jstack does. |
1025 |
> |
* Like Runnable, but with the freedom to throw anything. |
1026 |
> |
* junit folks had the same idea: |
1027 |
> |
* http://junit.org/junit5/docs/snapshot/api/org/junit/gen5/api/Executable.html |
1028 |
|
*/ |
1029 |
< |
static void printAllStackTraces() { |
671 |
< |
for (ThreadInfo info : |
672 |
< |
ManagementFactory.getThreadMXBean() |
673 |
< |
.dumpAllThreads(true, true)) |
674 |
< |
System.err.print(info); |
675 |
< |
} |
1029 |
> |
interface Action { public void run() throws Throwable; } |
1030 |
|
|
1031 |
|
/** |
1032 |
< |
* Checks that thread does not terminate within the default |
1033 |
< |
* millisecond delay of {@code timeoutMillis()}. |
1032 |
> |
* Runs all the given actions in parallel, failing if any fail. |
1033 |
> |
* Useful for running multiple variants of tests that are |
1034 |
> |
* necessarily individually slow because they must block. |
1035 |
|
*/ |
1036 |
< |
void assertThreadStaysAlive(Thread thread) { |
1037 |
< |
assertThreadStaysAlive(thread, timeoutMillis()); |
1036 |
> |
void testInParallel(Action ... actions) { |
1037 |
> |
ExecutorService pool = Executors.newCachedThreadPool(); |
1038 |
> |
try (PoolCleaner cleaner = cleaner(pool)) { |
1039 |
> |
ArrayList<Future<?>> futures = new ArrayList<>(actions.length); |
1040 |
> |
for (final Action action : actions) |
1041 |
> |
futures.add(pool.submit(new CheckedRunnable() { |
1042 |
> |
public void realRun() throws Throwable { action.run();}})); |
1043 |
> |
for (Future<?> future : futures) |
1044 |
> |
try { |
1045 |
> |
assertNull(future.get(LONG_DELAY_MS, MILLISECONDS)); |
1046 |
> |
} catch (ExecutionException ex) { |
1047 |
> |
threadUnexpectedException(ex.getCause()); |
1048 |
> |
} catch (Exception ex) { |
1049 |
> |
threadUnexpectedException(ex); |
1050 |
> |
} |
1051 |
> |
} |
1052 |
|
} |
1053 |
|
|
1054 |
|
/** |
1055 |
< |
* Checks that thread does not terminate within the given millisecond delay. |
1055 |
> |
* A debugging tool to print stack traces of most threads, as jstack does. |
1056 |
> |
* Uninteresting threads are filtered out. |
1057 |
|
*/ |
1058 |
< |
void assertThreadStaysAlive(Thread thread, long millis) { |
1059 |
< |
try { |
1060 |
< |
// No need to optimize the failing case via Thread.join. |
1061 |
< |
delay(millis); |
1062 |
< |
assertTrue(thread.isAlive()); |
1063 |
< |
} catch (InterruptedException fail) { |
1064 |
< |
fail("Unexpected InterruptedException"); |
1058 |
> |
static void dumpTestThreads() { |
1059 |
> |
SecurityManager sm = System.getSecurityManager(); |
1060 |
> |
if (sm != null) { |
1061 |
> |
try { |
1062 |
> |
System.setSecurityManager(null); |
1063 |
> |
} catch (SecurityException giveUp) { |
1064 |
> |
return; |
1065 |
> |
} |
1066 |
|
} |
696 |
– |
} |
1067 |
|
|
1068 |
< |
/** |
1069 |
< |
* Checks that the threads do not terminate within the default |
1070 |
< |
* millisecond delay of {@code timeoutMillis()}. |
1071 |
< |
*/ |
1072 |
< |
void assertThreadsStayAlive(Thread... threads) { |
1073 |
< |
assertThreadsStayAlive(timeoutMillis(), threads); |
1068 |
> |
ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); |
1069 |
> |
System.err.println("------ stacktrace dump start ------"); |
1070 |
> |
for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) { |
1071 |
> |
final String name = info.getThreadName(); |
1072 |
> |
String lockName; |
1073 |
> |
if ("Signal Dispatcher".equals(name)) |
1074 |
> |
continue; |
1075 |
> |
if ("Reference Handler".equals(name) |
1076 |
> |
&& (lockName = info.getLockName()) != null |
1077 |
> |
&& lockName.startsWith("java.lang.ref.Reference$Lock")) |
1078 |
> |
continue; |
1079 |
> |
if ("Finalizer".equals(name) |
1080 |
> |
&& (lockName = info.getLockName()) != null |
1081 |
> |
&& lockName.startsWith("java.lang.ref.ReferenceQueue$Lock")) |
1082 |
> |
continue; |
1083 |
> |
if ("checkForWedgedTest".equals(name)) |
1084 |
> |
continue; |
1085 |
> |
System.err.print(info); |
1086 |
> |
} |
1087 |
> |
System.err.println("------ stacktrace dump end ------"); |
1088 |
> |
|
1089 |
> |
if (sm != null) System.setSecurityManager(sm); |
1090 |
|
} |
1091 |
|
|
1092 |
|
/** |
1093 |
< |
* Checks that the threads do not terminate within the given millisecond delay. |
1093 |
> |
* Checks that thread eventually enters the expected blocked thread state. |
1094 |
|
*/ |
1095 |
< |
void assertThreadsStayAlive(long millis, Thread... threads) { |
1096 |
< |
try { |
1097 |
< |
// No need to optimize the failing case via Thread.join. |
1098 |
< |
delay(millis); |
1099 |
< |
for (Thread thread : threads) |
1100 |
< |
assertTrue(thread.isAlive()); |
1101 |
< |
} catch (InterruptedException fail) { |
1102 |
< |
fail("Unexpected InterruptedException"); |
1095 |
> |
void assertThreadBlocks(Thread thread, Thread.State expected) { |
1096 |
> |
// always sleep at least 1 ms, with high probability avoiding |
1097 |
> |
// transitory states |
1098 |
> |
for (long retries = LONG_DELAY_MS * 3 / 4; retries-->0; ) { |
1099 |
> |
try { delay(1); } |
1100 |
> |
catch (InterruptedException fail) { |
1101 |
> |
fail("Unexpected InterruptedException"); |
1102 |
> |
} |
1103 |
> |
Thread.State s = thread.getState(); |
1104 |
> |
if (s == expected) |
1105 |
> |
return; |
1106 |
> |
else if (s == Thread.State.TERMINATED) |
1107 |
> |
fail("Unexpected thread termination"); |
1108 |
|
} |
1109 |
+ |
fail("timed out waiting for thread to enter thread state " + expected); |
1110 |
|
} |
1111 |
|
|
1112 |
|
/** |
1147 |
|
} |
1148 |
|
|
1149 |
|
/** |
1150 |
+ |
* The maximum number of consecutive spurious wakeups we should |
1151 |
+ |
* tolerate (from APIs like LockSupport.park) before failing a test. |
1152 |
+ |
*/ |
1153 |
+ |
static final int MAX_SPURIOUS_WAKEUPS = 10; |
1154 |
+ |
|
1155 |
+ |
/** |
1156 |
|
* The number of elements to place in collections, arrays, etc. |
1157 |
|
*/ |
1158 |
|
public static final int SIZE = 20; |
1256 |
|
} |
1257 |
|
public void refresh() {} |
1258 |
|
public String toString() { |
1259 |
< |
List<Permission> ps = new ArrayList<Permission>(); |
1259 |
> |
List<Permission> ps = new ArrayList<>(); |
1260 |
|
for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();) |
1261 |
|
ps.add(e.nextElement()); |
1262 |
|
return "AdjustablePolicy with permissions " + ps; |
1286 |
|
* Sleeps until the given time has elapsed. |
1287 |
|
* Throws AssertionFailedError if interrupted. |
1288 |
|
*/ |
1289 |
< |
void sleep(long millis) { |
1289 |
> |
static void sleep(long millis) { |
1290 |
|
try { |
1291 |
|
delay(millis); |
1292 |
|
} catch (InterruptedException fail) { |
1302 |
|
* thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING. |
1303 |
|
*/ |
1304 |
|
void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) { |
1305 |
< |
long startTime = System.nanoTime(); |
1305 |
> |
long startTime = 0L; |
1306 |
|
for (;;) { |
1307 |
|
Thread.State s = thread.getState(); |
1308 |
|
if (s == Thread.State.BLOCKED || |
1311 |
|
return; |
1312 |
|
else if (s == Thread.State.TERMINATED) |
1313 |
|
fail("Unexpected thread termination"); |
1314 |
+ |
else if (startTime == 0L) |
1315 |
+ |
startTime = System.nanoTime(); |
1316 |
|
else if (millisElapsedSince(startTime) > timeoutMillis) { |
1317 |
|
threadAssertTrue(thread.isAlive()); |
1318 |
< |
return; |
1318 |
> |
fail("timed out waiting for thread to enter wait state"); |
1319 |
> |
} |
1320 |
> |
Thread.yield(); |
1321 |
> |
} |
1322 |
> |
} |
1323 |
> |
|
1324 |
> |
/** |
1325 |
> |
* Spin-waits up to the specified number of milliseconds for the given |
1326 |
> |
* thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING, |
1327 |
> |
* and additionally satisfy the given condition. |
1328 |
> |
*/ |
1329 |
> |
void waitForThreadToEnterWaitState( |
1330 |
> |
Thread thread, long timeoutMillis, Callable<Boolean> waitingForGodot) { |
1331 |
> |
long startTime = 0L; |
1332 |
> |
for (;;) { |
1333 |
> |
Thread.State s = thread.getState(); |
1334 |
> |
if (s == Thread.State.BLOCKED || |
1335 |
> |
s == Thread.State.WAITING || |
1336 |
> |
s == Thread.State.TIMED_WAITING) { |
1337 |
> |
try { |
1338 |
> |
if (waitingForGodot.call()) |
1339 |
> |
return; |
1340 |
> |
} catch (Throwable fail) { threadUnexpectedException(fail); } |
1341 |
> |
} |
1342 |
> |
else if (s == Thread.State.TERMINATED) |
1343 |
> |
fail("Unexpected thread termination"); |
1344 |
> |
else if (startTime == 0L) |
1345 |
> |
startTime = System.nanoTime(); |
1346 |
> |
else if (millisElapsedSince(startTime) > timeoutMillis) { |
1347 |
> |
threadAssertTrue(thread.isAlive()); |
1348 |
> |
fail("timed out waiting for thread to enter wait state"); |
1349 |
|
} |
1350 |
|
Thread.yield(); |
1351 |
|
} |
1352 |
|
} |
1353 |
|
|
1354 |
|
/** |
1355 |
< |
* Waits up to LONG_DELAY_MS for the given thread to enter a wait |
1356 |
< |
* state: BLOCKED, WAITING, or TIMED_WAITING. |
1355 |
> |
* Spin-waits up to LONG_DELAY_MS milliseconds for the given thread to |
1356 |
> |
* enter a wait state: BLOCKED, WAITING, or TIMED_WAITING. |
1357 |
|
*/ |
1358 |
|
void waitForThreadToEnterWaitState(Thread thread) { |
1359 |
|
waitForThreadToEnterWaitState(thread, LONG_DELAY_MS); |
1360 |
|
} |
1361 |
|
|
1362 |
|
/** |
1363 |
+ |
* Spin-waits up to LONG_DELAY_MS milliseconds for the given thread to |
1364 |
+ |
* enter a wait state: BLOCKED, WAITING, or TIMED_WAITING, |
1365 |
+ |
* and additionally satisfy the given condition. |
1366 |
+ |
*/ |
1367 |
+ |
void waitForThreadToEnterWaitState( |
1368 |
+ |
Thread thread, Callable<Boolean> waitingForGodot) { |
1369 |
+ |
waitForThreadToEnterWaitState(thread, LONG_DELAY_MS, waitingForGodot); |
1370 |
+ |
} |
1371 |
+ |
|
1372 |
+ |
/** |
1373 |
|
* Returns the number of milliseconds since time given by |
1374 |
|
* startNanoTime, which must have been previously returned from a |
1375 |
|
* call to {@link System#nanoTime()}. |
1431 |
|
} finally { |
1432 |
|
if (t.getState() != Thread.State.TERMINATED) { |
1433 |
|
t.interrupt(); |
1434 |
< |
fail("Test timed out"); |
1434 |
> |
threadFail("timed out waiting for thread to terminate"); |
1435 |
|
} |
1436 |
|
} |
1437 |
|
} |
1556 |
|
public static final String TEST_STRING = "a test string"; |
1557 |
|
|
1558 |
|
public static class StringTask implements Callable<String> { |
1559 |
< |
public String call() { return TEST_STRING; } |
1559 |
> |
final String value; |
1560 |
> |
public StringTask() { this(TEST_STRING); } |
1561 |
> |
public StringTask(String value) { this.value = value; } |
1562 |
> |
public String call() { return value; } |
1563 |
|
} |
1564 |
|
|
1565 |
|
public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) { |
1572 |
|
}}; |
1573 |
|
} |
1574 |
|
|
1575 |
< |
public Runnable awaiter(final CountDownLatch latch) { |
1575 |
> |
public Runnable countDowner(final CountDownLatch latch) { |
1576 |
|
return new CheckedRunnable() { |
1577 |
|
public void realRun() throws InterruptedException { |
1578 |
< |
await(latch); |
1578 |
> |
latch.countDown(); |
1579 |
|
}}; |
1580 |
|
} |
1581 |
|
|
1582 |
< |
public void await(CountDownLatch latch) { |
1582 |
> |
class LatchAwaiter extends CheckedRunnable { |
1583 |
> |
static final int NEW = 0; |
1584 |
> |
static final int RUNNING = 1; |
1585 |
> |
static final int DONE = 2; |
1586 |
> |
final CountDownLatch latch; |
1587 |
> |
int state = NEW; |
1588 |
> |
LatchAwaiter(CountDownLatch latch) { this.latch = latch; } |
1589 |
> |
public void realRun() throws InterruptedException { |
1590 |
> |
state = 1; |
1591 |
> |
await(latch); |
1592 |
> |
state = 2; |
1593 |
> |
} |
1594 |
> |
} |
1595 |
> |
|
1596 |
> |
public LatchAwaiter awaiter(CountDownLatch latch) { |
1597 |
> |
return new LatchAwaiter(latch); |
1598 |
> |
} |
1599 |
> |
|
1600 |
> |
public void await(CountDownLatch latch, long timeoutMillis) { |
1601 |
|
try { |
1602 |
< |
assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS)); |
1602 |
> |
if (!latch.await(timeoutMillis, MILLISECONDS)) |
1603 |
> |
fail("timed out waiting for CountDownLatch for " |
1604 |
> |
+ (timeoutMillis/1000) + " sec"); |
1605 |
|
} catch (Throwable fail) { |
1606 |
|
threadUnexpectedException(fail); |
1607 |
|
} |
1608 |
|
} |
1609 |
|
|
1610 |
+ |
public void await(CountDownLatch latch) { |
1611 |
+ |
await(latch, LONG_DELAY_MS); |
1612 |
+ |
} |
1613 |
+ |
|
1614 |
|
public void await(Semaphore semaphore) { |
1615 |
|
try { |
1616 |
< |
assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS)); |
1616 |
> |
if (!semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS)) |
1617 |
> |
fail("timed out waiting for Semaphore for " |
1618 |
> |
+ (LONG_DELAY_MS/1000) + " sec"); |
1619 |
> |
} catch (Throwable fail) { |
1620 |
> |
threadUnexpectedException(fail); |
1621 |
> |
} |
1622 |
> |
} |
1623 |
> |
|
1624 |
> |
public void await(CyclicBarrier barrier) { |
1625 |
> |
try { |
1626 |
> |
barrier.await(LONG_DELAY_MS, MILLISECONDS); |
1627 |
|
} catch (Throwable fail) { |
1628 |
|
threadUnexpectedException(fail); |
1629 |
|
} |
1652 |
|
public String call() { throw new NullPointerException(); } |
1653 |
|
} |
1654 |
|
|
1178 |
– |
public static class CallableOne implements Callable<Integer> { |
1179 |
– |
public Integer call() { return one; } |
1180 |
– |
} |
1181 |
– |
|
1182 |
– |
public class ShortRunnable extends CheckedRunnable { |
1183 |
– |
protected void realRun() throws Throwable { |
1184 |
– |
delay(SHORT_DELAY_MS); |
1185 |
– |
} |
1186 |
– |
} |
1187 |
– |
|
1188 |
– |
public class ShortInterruptedRunnable extends CheckedInterruptedRunnable { |
1189 |
– |
protected void realRun() throws InterruptedException { |
1190 |
– |
delay(SHORT_DELAY_MS); |
1191 |
– |
} |
1192 |
– |
} |
1193 |
– |
|
1194 |
– |
public class SmallRunnable extends CheckedRunnable { |
1195 |
– |
protected void realRun() throws Throwable { |
1196 |
– |
delay(SMALL_DELAY_MS); |
1197 |
– |
} |
1198 |
– |
} |
1199 |
– |
|
1655 |
|
public class SmallPossiblyInterruptedRunnable extends CheckedRunnable { |
1656 |
|
protected void realRun() { |
1657 |
|
try { |
1660 |
|
} |
1661 |
|
} |
1662 |
|
|
1208 |
– |
public class SmallCallable extends CheckedCallable { |
1209 |
– |
protected Object realCall() throws InterruptedException { |
1210 |
– |
delay(SMALL_DELAY_MS); |
1211 |
– |
return Boolean.TRUE; |
1212 |
– |
} |
1213 |
– |
} |
1214 |
– |
|
1215 |
– |
public class MediumRunnable extends CheckedRunnable { |
1216 |
– |
protected void realRun() throws Throwable { |
1217 |
– |
delay(MEDIUM_DELAY_MS); |
1218 |
– |
} |
1219 |
– |
} |
1220 |
– |
|
1221 |
– |
public class MediumInterruptedRunnable extends CheckedInterruptedRunnable { |
1222 |
– |
protected void realRun() throws InterruptedException { |
1223 |
– |
delay(MEDIUM_DELAY_MS); |
1224 |
– |
} |
1225 |
– |
} |
1226 |
– |
|
1663 |
|
public Runnable possiblyInterruptedRunnable(final long timeoutMillis) { |
1664 |
|
return new CheckedRunnable() { |
1665 |
|
protected void realRun() { |
1669 |
|
}}; |
1670 |
|
} |
1671 |
|
|
1236 |
– |
public class MediumPossiblyInterruptedRunnable extends CheckedRunnable { |
1237 |
– |
protected void realRun() { |
1238 |
– |
try { |
1239 |
– |
delay(MEDIUM_DELAY_MS); |
1240 |
– |
} catch (InterruptedException ok) {} |
1241 |
– |
} |
1242 |
– |
} |
1243 |
– |
|
1244 |
– |
public class LongPossiblyInterruptedRunnable extends CheckedRunnable { |
1245 |
– |
protected void realRun() { |
1246 |
– |
try { |
1247 |
– |
delay(LONG_DELAY_MS); |
1248 |
– |
} catch (InterruptedException ok) {} |
1249 |
– |
} |
1250 |
– |
} |
1251 |
– |
|
1672 |
|
/** |
1673 |
|
* For use as ThreadFactory in constructors |
1674 |
|
*/ |
1682 |
|
boolean isDone(); |
1683 |
|
} |
1684 |
|
|
1265 |
– |
public static TrackedRunnable trackedRunnable(final long timeoutMillis) { |
1266 |
– |
return new TrackedRunnable() { |
1267 |
– |
private volatile boolean done = false; |
1268 |
– |
public boolean isDone() { return done; } |
1269 |
– |
public void run() { |
1270 |
– |
try { |
1271 |
– |
delay(timeoutMillis); |
1272 |
– |
done = true; |
1273 |
– |
} catch (InterruptedException ok) {} |
1274 |
– |
} |
1275 |
– |
}; |
1276 |
– |
} |
1277 |
– |
|
1278 |
– |
public static class TrackedShortRunnable implements Runnable { |
1279 |
– |
public volatile boolean done = false; |
1280 |
– |
public void run() { |
1281 |
– |
try { |
1282 |
– |
delay(SHORT_DELAY_MS); |
1283 |
– |
done = true; |
1284 |
– |
} catch (InterruptedException ok) {} |
1285 |
– |
} |
1286 |
– |
} |
1287 |
– |
|
1288 |
– |
public static class TrackedSmallRunnable implements Runnable { |
1289 |
– |
public volatile boolean done = false; |
1290 |
– |
public void run() { |
1291 |
– |
try { |
1292 |
– |
delay(SMALL_DELAY_MS); |
1293 |
– |
done = true; |
1294 |
– |
} catch (InterruptedException ok) {} |
1295 |
– |
} |
1296 |
– |
} |
1297 |
– |
|
1298 |
– |
public static class TrackedMediumRunnable implements Runnable { |
1299 |
– |
public volatile boolean done = false; |
1300 |
– |
public void run() { |
1301 |
– |
try { |
1302 |
– |
delay(MEDIUM_DELAY_MS); |
1303 |
– |
done = true; |
1304 |
– |
} catch (InterruptedException ok) {} |
1305 |
– |
} |
1306 |
– |
} |
1307 |
– |
|
1308 |
– |
public static class TrackedLongRunnable implements Runnable { |
1309 |
– |
public volatile boolean done = false; |
1310 |
– |
public void run() { |
1311 |
– |
try { |
1312 |
– |
delay(LONG_DELAY_MS); |
1313 |
– |
done = true; |
1314 |
– |
} catch (InterruptedException ok) {} |
1315 |
– |
} |
1316 |
– |
} |
1317 |
– |
|
1685 |
|
public static class TrackedNoOpRunnable implements Runnable { |
1686 |
|
public volatile boolean done = false; |
1687 |
|
public void run() { |
1689 |
|
} |
1690 |
|
} |
1691 |
|
|
1325 |
– |
public static class TrackedCallable implements Callable { |
1326 |
– |
public volatile boolean done = false; |
1327 |
– |
public Object call() { |
1328 |
– |
try { |
1329 |
– |
delay(SMALL_DELAY_MS); |
1330 |
– |
done = true; |
1331 |
– |
} catch (InterruptedException ok) {} |
1332 |
– |
return Boolean.TRUE; |
1333 |
– |
} |
1334 |
– |
} |
1335 |
– |
|
1692 |
|
/** |
1693 |
|
* Analog of CheckedRunnable for RecursiveAction |
1694 |
|
*/ |
1732 |
|
* A CyclicBarrier that uses timed await and fails with |
1733 |
|
* AssertionFailedErrors instead of throwing checked exceptions. |
1734 |
|
*/ |
1735 |
< |
public class CheckedBarrier extends CyclicBarrier { |
1735 |
> |
public static class CheckedBarrier extends CyclicBarrier { |
1736 |
|
public CheckedBarrier(int parties) { super(parties); } |
1737 |
|
|
1738 |
|
public int await() { |
1755 |
|
assertEquals(0, q.size()); |
1756 |
|
assertNull(q.peek()); |
1757 |
|
assertNull(q.poll()); |
1758 |
< |
assertNull(q.poll(0, MILLISECONDS)); |
1758 |
> |
assertNull(q.poll(randomExpiredTimeout(), randomTimeUnit())); |
1759 |
|
assertEquals(q.toString(), "[]"); |
1760 |
|
assertTrue(Arrays.equals(q.toArray(), new Object[0])); |
1761 |
|
assertFalse(q.iterator().hasNext()); |
1796 |
|
} |
1797 |
|
} |
1798 |
|
|
1799 |
+ |
void assertImmutable(final Object o) { |
1800 |
+ |
if (o instanceof Collection) { |
1801 |
+ |
assertThrows( |
1802 |
+ |
UnsupportedOperationException.class, |
1803 |
+ |
new Runnable() { public void run() { |
1804 |
+ |
((Collection) o).add(null);}}); |
1805 |
+ |
} |
1806 |
+ |
} |
1807 |
+ |
|
1808 |
|
@SuppressWarnings("unchecked") |
1809 |
|
<T> T serialClone(T o) { |
1810 |
|
try { |
1811 |
|
ObjectInputStream ois = new ObjectInputStream |
1812 |
|
(new ByteArrayInputStream(serialBytes(o))); |
1813 |
|
T clone = (T) ois.readObject(); |
1814 |
+ |
if (o == clone) assertImmutable(o); |
1815 |
|
assertSame(o.getClass(), clone.getClass()); |
1816 |
|
return clone; |
1817 |
|
} catch (Throwable fail) { |
1820 |
|
} |
1821 |
|
} |
1822 |
|
|
1823 |
+ |
/** |
1824 |
+ |
* A version of serialClone that leaves error handling (for |
1825 |
+ |
* e.g. NotSerializableException) up to the caller. |
1826 |
+ |
*/ |
1827 |
+ |
@SuppressWarnings("unchecked") |
1828 |
+ |
<T> T serialClonePossiblyFailing(T o) |
1829 |
+ |
throws ReflectiveOperationException, java.io.IOException { |
1830 |
+ |
ByteArrayOutputStream bos = new ByteArrayOutputStream(); |
1831 |
+ |
ObjectOutputStream oos = new ObjectOutputStream(bos); |
1832 |
+ |
oos.writeObject(o); |
1833 |
+ |
oos.flush(); |
1834 |
+ |
oos.close(); |
1835 |
+ |
ObjectInputStream ois = new ObjectInputStream |
1836 |
+ |
(new ByteArrayInputStream(bos.toByteArray())); |
1837 |
+ |
T clone = (T) ois.readObject(); |
1838 |
+ |
if (o == clone) assertImmutable(o); |
1839 |
+ |
assertSame(o.getClass(), clone.getClass()); |
1840 |
+ |
return clone; |
1841 |
+ |
} |
1842 |
+ |
|
1843 |
+ |
/** |
1844 |
+ |
* If o implements Cloneable and has a public clone method, |
1845 |
+ |
* returns a clone of o, else null. |
1846 |
+ |
*/ |
1847 |
+ |
@SuppressWarnings("unchecked") |
1848 |
+ |
<T> T cloneableClone(T o) { |
1849 |
+ |
if (!(o instanceof Cloneable)) return null; |
1850 |
+ |
final T clone; |
1851 |
+ |
try { |
1852 |
+ |
clone = (T) o.getClass().getMethod("clone").invoke(o); |
1853 |
+ |
} catch (NoSuchMethodException ok) { |
1854 |
+ |
return null; |
1855 |
+ |
} catch (ReflectiveOperationException unexpected) { |
1856 |
+ |
throw new Error(unexpected); |
1857 |
+ |
} |
1858 |
+ |
assertNotSame(o, clone); // not 100% guaranteed by spec |
1859 |
+ |
assertSame(o.getClass(), clone.getClass()); |
1860 |
+ |
return clone; |
1861 |
+ |
} |
1862 |
+ |
|
1863 |
|
public void assertThrows(Class<? extends Throwable> expectedExceptionClass, |
1864 |
|
Runnable... throwingActions) { |
1865 |
|
for (Runnable throwingAction : throwingActions) { |
1888 |
|
} catch (NoSuchElementException success) {} |
1889 |
|
assertFalse(it.hasNext()); |
1890 |
|
} |
1891 |
+ |
|
1892 |
+ |
public <T> Callable<T> callableThrowing(final Exception ex) { |
1893 |
+ |
return new Callable<T>() { public T call() throws Exception { throw ex; }}; |
1894 |
+ |
} |
1895 |
+ |
|
1896 |
+ |
public Runnable runnableThrowing(final RuntimeException ex) { |
1897 |
+ |
return new Runnable() { public void run() { throw ex; }}; |
1898 |
+ |
} |
1899 |
+ |
|
1900 |
+ |
/** A reusable thread pool to be shared by tests. */ |
1901 |
+ |
static final ExecutorService cachedThreadPool = |
1902 |
+ |
new ThreadPoolExecutor(0, Integer.MAX_VALUE, |
1903 |
+ |
1000L, MILLISECONDS, |
1904 |
+ |
new SynchronousQueue<Runnable>()); |
1905 |
+ |
|
1906 |
+ |
static <T> void shuffle(T[] array) { |
1907 |
+ |
Collections.shuffle(Arrays.asList(array), ThreadLocalRandom.current()); |
1908 |
+ |
} |
1909 |
+ |
|
1910 |
+ |
/** |
1911 |
+ |
* Returns the same String as would be returned by {@link |
1912 |
+ |
* Object#toString}, whether or not the given object's class |
1913 |
+ |
* overrides toString(). |
1914 |
+ |
* |
1915 |
+ |
* @see System#identityHashCode |
1916 |
+ |
*/ |
1917 |
+ |
static String identityString(Object x) { |
1918 |
+ |
return x.getClass().getName() |
1919 |
+ |
+ "@" + Integer.toHexString(System.identityHashCode(x)); |
1920 |
+ |
} |
1921 |
+ |
|
1922 |
+ |
// --- Shared assertions for Executor tests --- |
1923 |
+ |
|
1924 |
+ |
/** |
1925 |
+ |
* Returns maximum number of tasks that can be submitted to given |
1926 |
+ |
* pool (with bounded queue) before saturation (when submission |
1927 |
+ |
* throws RejectedExecutionException). |
1928 |
+ |
*/ |
1929 |
+ |
static final int saturatedSize(ThreadPoolExecutor pool) { |
1930 |
+ |
BlockingQueue<Runnable> q = pool.getQueue(); |
1931 |
+ |
return pool.getMaximumPoolSize() + q.size() + q.remainingCapacity(); |
1932 |
+ |
} |
1933 |
+ |
|
1934 |
+ |
@SuppressWarnings("FutureReturnValueIgnored") |
1935 |
+ |
void assertNullTaskSubmissionThrowsNullPointerException(Executor e) { |
1936 |
+ |
try { |
1937 |
+ |
e.execute((Runnable) null); |
1938 |
+ |
shouldThrow(); |
1939 |
+ |
} catch (NullPointerException success) {} |
1940 |
+ |
|
1941 |
+ |
if (! (e instanceof ExecutorService)) return; |
1942 |
+ |
ExecutorService es = (ExecutorService) e; |
1943 |
+ |
try { |
1944 |
+ |
es.submit((Runnable) null); |
1945 |
+ |
shouldThrow(); |
1946 |
+ |
} catch (NullPointerException success) {} |
1947 |
+ |
try { |
1948 |
+ |
es.submit((Runnable) null, Boolean.TRUE); |
1949 |
+ |
shouldThrow(); |
1950 |
+ |
} catch (NullPointerException success) {} |
1951 |
+ |
try { |
1952 |
+ |
es.submit((Callable) null); |
1953 |
+ |
shouldThrow(); |
1954 |
+ |
} catch (NullPointerException success) {} |
1955 |
+ |
|
1956 |
+ |
if (! (e instanceof ScheduledExecutorService)) return; |
1957 |
+ |
ScheduledExecutorService ses = (ScheduledExecutorService) e; |
1958 |
+ |
try { |
1959 |
+ |
ses.schedule((Runnable) null, |
1960 |
+ |
randomTimeout(), randomTimeUnit()); |
1961 |
+ |
shouldThrow(); |
1962 |
+ |
} catch (NullPointerException success) {} |
1963 |
+ |
try { |
1964 |
+ |
ses.schedule((Callable) null, |
1965 |
+ |
randomTimeout(), randomTimeUnit()); |
1966 |
+ |
shouldThrow(); |
1967 |
+ |
} catch (NullPointerException success) {} |
1968 |
+ |
try { |
1969 |
+ |
ses.scheduleAtFixedRate((Runnable) null, |
1970 |
+ |
randomTimeout(), LONG_DELAY_MS, MILLISECONDS); |
1971 |
+ |
shouldThrow(); |
1972 |
+ |
} catch (NullPointerException success) {} |
1973 |
+ |
try { |
1974 |
+ |
ses.scheduleWithFixedDelay((Runnable) null, |
1975 |
+ |
randomTimeout(), LONG_DELAY_MS, MILLISECONDS); |
1976 |
+ |
shouldThrow(); |
1977 |
+ |
} catch (NullPointerException success) {} |
1978 |
+ |
} |
1979 |
+ |
|
1980 |
+ |
void setRejectedExecutionHandler( |
1981 |
+ |
ThreadPoolExecutor p, RejectedExecutionHandler handler) { |
1982 |
+ |
p.setRejectedExecutionHandler(handler); |
1983 |
+ |
assertSame(handler, p.getRejectedExecutionHandler()); |
1984 |
+ |
} |
1985 |
+ |
|
1986 |
+ |
void assertTaskSubmissionsAreRejected(ThreadPoolExecutor p) { |
1987 |
+ |
final RejectedExecutionHandler savedHandler = p.getRejectedExecutionHandler(); |
1988 |
+ |
final long savedTaskCount = p.getTaskCount(); |
1989 |
+ |
final long savedCompletedTaskCount = p.getCompletedTaskCount(); |
1990 |
+ |
final int savedQueueSize = p.getQueue().size(); |
1991 |
+ |
final boolean stock = (p.getClass().getClassLoader() == null); |
1992 |
+ |
|
1993 |
+ |
Runnable r = () -> {}; |
1994 |
+ |
Callable<Boolean> c = () -> Boolean.TRUE; |
1995 |
+ |
|
1996 |
+ |
class Recorder implements RejectedExecutionHandler { |
1997 |
+ |
public volatile Runnable r = null; |
1998 |
+ |
public volatile ThreadPoolExecutor p = null; |
1999 |
+ |
public void reset() { r = null; p = null; } |
2000 |
+ |
public void rejectedExecution(Runnable r, ThreadPoolExecutor p) { |
2001 |
+ |
assertNull(this.r); |
2002 |
+ |
assertNull(this.p); |
2003 |
+ |
this.r = r; |
2004 |
+ |
this.p = p; |
2005 |
+ |
} |
2006 |
+ |
} |
2007 |
+ |
|
2008 |
+ |
// check custom handler is invoked exactly once per task |
2009 |
+ |
Recorder recorder = new Recorder(); |
2010 |
+ |
setRejectedExecutionHandler(p, recorder); |
2011 |
+ |
for (int i = 2; i--> 0; ) { |
2012 |
+ |
recorder.reset(); |
2013 |
+ |
p.execute(r); |
2014 |
+ |
if (stock && p.getClass() == ThreadPoolExecutor.class) |
2015 |
+ |
assertSame(r, recorder.r); |
2016 |
+ |
assertSame(p, recorder.p); |
2017 |
+ |
|
2018 |
+ |
recorder.reset(); |
2019 |
+ |
assertFalse(p.submit(r).isDone()); |
2020 |
+ |
if (stock) assertTrue(!((FutureTask) recorder.r).isDone()); |
2021 |
+ |
assertSame(p, recorder.p); |
2022 |
+ |
|
2023 |
+ |
recorder.reset(); |
2024 |
+ |
assertFalse(p.submit(r, Boolean.TRUE).isDone()); |
2025 |
+ |
if (stock) assertTrue(!((FutureTask) recorder.r).isDone()); |
2026 |
+ |
assertSame(p, recorder.p); |
2027 |
+ |
|
2028 |
+ |
recorder.reset(); |
2029 |
+ |
assertFalse(p.submit(c).isDone()); |
2030 |
+ |
if (stock) assertTrue(!((FutureTask) recorder.r).isDone()); |
2031 |
+ |
assertSame(p, recorder.p); |
2032 |
+ |
|
2033 |
+ |
if (p instanceof ScheduledExecutorService) { |
2034 |
+ |
ScheduledExecutorService s = (ScheduledExecutorService) p; |
2035 |
+ |
ScheduledFuture<?> future; |
2036 |
+ |
|
2037 |
+ |
recorder.reset(); |
2038 |
+ |
future = s.schedule(r, 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.schedule(c, randomTimeout(), randomTimeUnit()); |
2045 |
+ |
assertFalse(future.isDone()); |
2046 |
+ |
if (stock) assertTrue(!((FutureTask) recorder.r).isDone()); |
2047 |
+ |
assertSame(p, recorder.p); |
2048 |
+ |
|
2049 |
+ |
recorder.reset(); |
2050 |
+ |
future = s.scheduleAtFixedRate(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 |
+ |
recorder.reset(); |
2056 |
+ |
future = s.scheduleWithFixedDelay(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS); |
2057 |
+ |
assertFalse(future.isDone()); |
2058 |
+ |
if (stock) assertTrue(!((FutureTask) recorder.r).isDone()); |
2059 |
+ |
assertSame(p, recorder.p); |
2060 |
+ |
} |
2061 |
+ |
} |
2062 |
+ |
|
2063 |
+ |
// Checking our custom handler above should be sufficient, but |
2064 |
+ |
// we add some integration tests of standard handlers. |
2065 |
+ |
final AtomicReference<Thread> thread = new AtomicReference<>(); |
2066 |
+ |
final Runnable setThread = () -> thread.set(Thread.currentThread()); |
2067 |
+ |
|
2068 |
+ |
setRejectedExecutionHandler(p, new ThreadPoolExecutor.AbortPolicy()); |
2069 |
+ |
try { |
2070 |
+ |
p.execute(setThread); |
2071 |
+ |
shouldThrow(); |
2072 |
+ |
} catch (RejectedExecutionException success) {} |
2073 |
+ |
assertNull(thread.get()); |
2074 |
+ |
|
2075 |
+ |
setRejectedExecutionHandler(p, new ThreadPoolExecutor.DiscardPolicy()); |
2076 |
+ |
p.execute(setThread); |
2077 |
+ |
assertNull(thread.get()); |
2078 |
+ |
|
2079 |
+ |
setRejectedExecutionHandler(p, new ThreadPoolExecutor.CallerRunsPolicy()); |
2080 |
+ |
p.execute(setThread); |
2081 |
+ |
if (p.isShutdown()) |
2082 |
+ |
assertNull(thread.get()); |
2083 |
+ |
else |
2084 |
+ |
assertSame(Thread.currentThread(), thread.get()); |
2085 |
+ |
|
2086 |
+ |
setRejectedExecutionHandler(p, savedHandler); |
2087 |
+ |
|
2088 |
+ |
// check that pool was not perturbed by handlers |
2089 |
+ |
assertEquals(savedTaskCount, p.getTaskCount()); |
2090 |
+ |
assertEquals(savedCompletedTaskCount, p.getCompletedTaskCount()); |
2091 |
+ |
assertEquals(savedQueueSize, p.getQueue().size()); |
2092 |
+ |
} |
2093 |
|
} |