6 |
|
* Pat Fisher, Mike Judd. |
7 |
|
*/ |
8 |
|
|
9 |
+ |
/* |
10 |
+ |
* @test |
11 |
+ |
* @summary JSR-166 tck tests |
12 |
+ |
* @modules java.management |
13 |
+ |
* @build * |
14 |
+ |
* @run junit/othervm/timeout=1000 -Djsr166.testImplementationDetails=true JSR166TestCase |
15 |
+ |
* @run junit/othervm/timeout=1000 -Djava.util.concurrent.ForkJoinPool.common.parallelism=0 -Djsr166.testImplementationDetails=true JSR166TestCase |
16 |
+ |
*/ |
17 |
+ |
|
18 |
|
import static java.util.concurrent.TimeUnit.MILLISECONDS; |
19 |
+ |
import static java.util.concurrent.TimeUnit.MINUTES; |
20 |
|
import static java.util.concurrent.TimeUnit.NANOSECONDS; |
21 |
|
|
22 |
|
import java.io.ByteArrayInputStream; |
25 |
|
import java.io.ObjectOutputStream; |
26 |
|
import java.lang.management.ManagementFactory; |
27 |
|
import java.lang.management.ThreadInfo; |
28 |
+ |
import java.lang.management.ThreadMXBean; |
29 |
|
import java.lang.reflect.Constructor; |
30 |
|
import java.lang.reflect.Method; |
31 |
|
import java.lang.reflect.Modifier; |
32 |
+ |
import java.nio.file.Files; |
33 |
+ |
import java.nio.file.Paths; |
34 |
|
import java.security.CodeSource; |
35 |
|
import java.security.Permission; |
36 |
|
import java.security.PermissionCollection; |
53 |
|
import java.util.concurrent.ExecutionException; |
54 |
|
import java.util.concurrent.Executors; |
55 |
|
import java.util.concurrent.ExecutorService; |
56 |
+ |
import java.util.concurrent.ForkJoinPool; |
57 |
|
import java.util.concurrent.Future; |
58 |
|
import java.util.concurrent.RecursiveAction; |
59 |
|
import java.util.concurrent.RecursiveTask; |
60 |
|
import java.util.concurrent.RejectedExecutionHandler; |
61 |
|
import java.util.concurrent.Semaphore; |
62 |
+ |
import java.util.concurrent.SynchronousQueue; |
63 |
|
import java.util.concurrent.ThreadFactory; |
64 |
|
import java.util.concurrent.ThreadPoolExecutor; |
65 |
|
import java.util.concurrent.TimeoutException; |
66 |
+ |
import java.util.concurrent.atomic.AtomicBoolean; |
67 |
|
import java.util.concurrent.atomic.AtomicReference; |
68 |
+ |
import java.util.regex.Matcher; |
69 |
|
import java.util.regex.Pattern; |
70 |
|
|
71 |
|
import junit.framework.AssertionFailedError; |
84 |
|
* |
85 |
|
* <ol> |
86 |
|
* |
87 |
< |
* <li> All assertions in code running in generated threads must use |
87 |
> |
* <li>All assertions in code running in generated threads must use |
88 |
|
* the forms {@link #threadFail}, {@link #threadAssertTrue}, {@link |
89 |
|
* #threadAssertEquals}, or {@link #threadAssertNull}, (not |
90 |
|
* {@code fail}, {@code assertTrue}, etc.) It is OK (but not |
91 |
|
* particularly recommended) for other code to use these forms too. |
92 |
|
* Only the most typically used JUnit assertion methods are defined |
93 |
< |
* this way, but enough to live with.</li> |
93 |
> |
* this way, but enough to live with. |
94 |
|
* |
95 |
< |
* <li> If you override {@link #setUp} or {@link #tearDown}, make sure |
95 |
> |
* <li>If you override {@link #setUp} or {@link #tearDown}, make sure |
96 |
|
* to invoke {@code super.setUp} and {@code super.tearDown} within |
97 |
|
* them. These methods are used to clear and check for thread |
98 |
< |
* assertion failures.</li> |
98 |
> |
* assertion failures. |
99 |
|
* |
100 |
|
* <li>All delays and timeouts must use one of the constants {@code |
101 |
|
* SHORT_DELAY_MS}, {@code SMALL_DELAY_MS}, {@code MEDIUM_DELAY_MS}, |
106 |
|
* is always discriminable as larger than SHORT and smaller than |
107 |
|
* MEDIUM. And so on. These constants are set to conservative values, |
108 |
|
* but even so, if there is ever any doubt, they can all be increased |
109 |
< |
* in one spot to rerun tests on slower platforms.</li> |
109 |
> |
* in one spot to rerun tests on slower platforms. |
110 |
|
* |
111 |
< |
* <li> All threads generated must be joined inside each test case |
111 |
> |
* <li>All threads generated must be joined inside each test case |
112 |
|
* method (or {@code fail} to do so) before returning from the |
113 |
|
* method. The {@code joinPool} method can be used to do this when |
114 |
< |
* using Executors.</li> |
114 |
> |
* using Executors. |
115 |
|
* |
116 |
|
* </ol> |
117 |
|
* |
118 |
|
* <p><b>Other notes</b> |
119 |
|
* <ul> |
120 |
|
* |
121 |
< |
* <li> Usually, there is one testcase method per JSR166 method |
121 |
> |
* <li>Usually, there is one testcase method per JSR166 method |
122 |
|
* covering "normal" operation, and then as many exception-testing |
123 |
|
* methods as there are exceptions the method can throw. Sometimes |
124 |
|
* there are multiple tests per JSR166 method when the different |
125 |
|
* "normal" behaviors differ significantly. And sometimes testcases |
126 |
< |
* cover multiple methods when they cannot be tested in |
110 |
< |
* isolation.</li> |
126 |
> |
* cover multiple methods when they cannot be tested in isolation. |
127 |
|
* |
128 |
< |
* <li> The documentation style for testcases is to provide as javadoc |
128 |
> |
* <li>The documentation style for testcases is to provide as javadoc |
129 |
|
* a simple sentence or two describing the property that the testcase |
130 |
|
* method purports to test. The javadocs do not say anything about how |
131 |
< |
* the property is tested. To find out, read the code.</li> |
131 |
> |
* the property is tested. To find out, read the code. |
132 |
|
* |
133 |
< |
* <li> These tests are "conformance tests", and do not attempt to |
133 |
> |
* <li>These tests are "conformance tests", and do not attempt to |
134 |
|
* test throughput, latency, scalability or other performance factors |
135 |
|
* (see the separate "jtreg" tests for a set intended to check these |
136 |
|
* for the most central aspects of functionality.) So, most tests use |
137 |
|
* the smallest sensible numbers of threads, collection sizes, etc |
138 |
< |
* needed to check basic conformance.</li> |
138 |
> |
* needed to check basic conformance. |
139 |
|
* |
140 |
|
* <li>The test classes currently do not declare inclusion in |
141 |
|
* any particular package to simplify things for people integrating |
142 |
< |
* them in TCK test suites.</li> |
142 |
> |
* them in TCK test suites. |
143 |
|
* |
144 |
< |
* <li> As a convenience, the {@code main} of this class (JSR166TestCase) |
145 |
< |
* runs all JSR166 unit tests.</li> |
144 |
> |
* <li>As a convenience, the {@code main} of this class (JSR166TestCase) |
145 |
> |
* runs all JSR166 unit tests. |
146 |
|
* |
147 |
|
* </ul> |
148 |
|
*/ |
186 |
|
private static final int suiteRuns = |
187 |
|
Integer.getInteger("jsr166.suiteRuns", 1); |
188 |
|
|
189 |
+ |
/** |
190 |
+ |
* Returns the value of the system property, or NaN if not defined. |
191 |
+ |
*/ |
192 |
+ |
private static float systemPropertyValue(String name) { |
193 |
+ |
String floatString = System.getProperty(name); |
194 |
+ |
if (floatString == null) |
195 |
+ |
return Float.NaN; |
196 |
+ |
try { |
197 |
+ |
return Float.parseFloat(floatString); |
198 |
+ |
} catch (NumberFormatException ex) { |
199 |
+ |
throw new IllegalArgumentException( |
200 |
+ |
String.format("Bad float value in system property %s=%s", |
201 |
+ |
name, floatString)); |
202 |
+ |
} |
203 |
+ |
} |
204 |
+ |
|
205 |
+ |
/** |
206 |
+ |
* The scaling factor to apply to standard delays used in tests. |
207 |
+ |
* May be initialized from any of: |
208 |
+ |
* - the "jsr166.delay.factor" system property |
209 |
+ |
* - the "test.timeout.factor" system property (as used by jtreg) |
210 |
+ |
* See: http://openjdk.java.net/jtreg/tag-spec.html |
211 |
+ |
* - hard-coded fuzz factor when using a known slowpoke VM |
212 |
+ |
*/ |
213 |
+ |
private static final float delayFactor = delayFactor(); |
214 |
+ |
|
215 |
+ |
private static float delayFactor() { |
216 |
+ |
float x; |
217 |
+ |
if (!Float.isNaN(x = systemPropertyValue("jsr166.delay.factor"))) |
218 |
+ |
return x; |
219 |
+ |
if (!Float.isNaN(x = systemPropertyValue("test.timeout.factor"))) |
220 |
+ |
return x; |
221 |
+ |
String prop = System.getProperty("java.vm.version"); |
222 |
+ |
if (prop != null && prop.matches(".*debug.*")) |
223 |
+ |
return 4.0f; // How much slower is fastdebug than product?! |
224 |
+ |
return 1.0f; |
225 |
+ |
} |
226 |
+ |
|
227 |
|
public JSR166TestCase() { super(); } |
228 |
|
public JSR166TestCase(String name) { super(name); } |
229 |
|
|
239 |
|
return (regex == null) ? null : Pattern.compile(regex); |
240 |
|
} |
241 |
|
|
242 |
< |
protected void runTest() throws Throwable { |
242 |
> |
// Instrumentation to debug very rare, but very annoying hung test runs. |
243 |
> |
static volatile TestCase currentTestCase; |
244 |
> |
// static volatile int currentRun = 0; |
245 |
> |
static { |
246 |
> |
Runnable checkForWedgedTest = new Runnable() { public void run() { |
247 |
> |
// Avoid spurious reports with enormous runsPerTest. |
248 |
> |
// A single test case run should never take more than 1 second. |
249 |
> |
// But let's cap it at the high end too ... |
250 |
> |
final int timeoutMinutes = |
251 |
> |
Math.min(15, Math.max(runsPerTest / 60, 1)); |
252 |
> |
for (TestCase lastTestCase = currentTestCase;;) { |
253 |
> |
try { MINUTES.sleep(timeoutMinutes); } |
254 |
> |
catch (InterruptedException unexpected) { break; } |
255 |
> |
if (lastTestCase == currentTestCase) { |
256 |
> |
System.err.printf( |
257 |
> |
"Looks like we're stuck running test: %s%n", |
258 |
> |
lastTestCase); |
259 |
> |
// System.err.printf( |
260 |
> |
// "Looks like we're stuck running test: %s (%d/%d)%n", |
261 |
> |
// lastTestCase, currentRun, runsPerTest); |
262 |
> |
// System.err.println("availableProcessors=" + |
263 |
> |
// Runtime.getRuntime().availableProcessors()); |
264 |
> |
// System.err.printf("cpu model = %s%n", cpuModel()); |
265 |
> |
dumpTestThreads(); |
266 |
> |
// one stack dump is probably enough; more would be spam |
267 |
> |
break; |
268 |
> |
} |
269 |
> |
lastTestCase = currentTestCase; |
270 |
> |
}}}; |
271 |
> |
Thread thread = new Thread(checkForWedgedTest, "checkForWedgedTest"); |
272 |
> |
thread.setDaemon(true); |
273 |
> |
thread.start(); |
274 |
> |
} |
275 |
> |
|
276 |
> |
// public static String cpuModel() { |
277 |
> |
// try { |
278 |
> |
// Matcher matcher = Pattern.compile("model name\\s*: (.*)") |
279 |
> |
// .matcher(new String( |
280 |
> |
// Files.readAllBytes(Paths.get("/proc/cpuinfo")), "UTF-8")); |
281 |
> |
// matcher.find(); |
282 |
> |
// return matcher.group(1); |
283 |
> |
// } catch (Exception ex) { return null; } |
284 |
> |
// } |
285 |
> |
|
286 |
> |
public void runBare() throws Throwable { |
287 |
> |
currentTestCase = this; |
288 |
|
if (methodFilter == null |
289 |
< |
|| methodFilter.matcher(toString()).find()) { |
290 |
< |
for (int i = 0; i < runsPerTest; i++) { |
291 |
< |
if (profileTests) |
292 |
< |
runTestProfiled(); |
293 |
< |
else |
294 |
< |
super.runTest(); |
295 |
< |
} |
289 |
> |
|| methodFilter.matcher(toString()).find()) |
290 |
> |
super.runBare(); |
291 |
> |
} |
292 |
> |
|
293 |
> |
protected void runTest() throws Throwable { |
294 |
> |
for (int i = 0; i < runsPerTest; i++) { |
295 |
> |
// currentRun = i; |
296 |
> |
if (profileTests) |
297 |
> |
runTestProfiled(); |
298 |
> |
else |
299 |
> |
super.runTest(); |
300 |
|
} |
301 |
|
} |
302 |
|
|
303 |
|
protected void runTestProfiled() throws Throwable { |
304 |
< |
// Warmup run, notably to trigger all needed classloading. |
305 |
< |
super.runTest(); |
203 |
< |
long t0 = System.nanoTime(); |
204 |
< |
try { |
304 |
> |
for (int i = 0; i < 2; i++) { |
305 |
> |
long startTime = System.nanoTime(); |
306 |
|
super.runTest(); |
307 |
< |
} finally { |
308 |
< |
long elapsedMillis = millisElapsedSince(t0); |
309 |
< |
if (elapsedMillis >= profileThreshold) |
307 |
> |
long elapsedMillis = millisElapsedSince(startTime); |
308 |
> |
if (elapsedMillis < profileThreshold) |
309 |
> |
break; |
310 |
> |
// Never report first run of any test; treat it as a |
311 |
> |
// warmup run, notably to trigger all needed classloading, |
312 |
> |
if (i > 0) |
313 |
|
System.out.printf("%n%s: %d%n", toString(), elapsedMillis); |
314 |
|
} |
315 |
|
} |
321 |
|
main(suite(), args); |
322 |
|
} |
323 |
|
|
324 |
+ |
static class PithyResultPrinter extends junit.textui.ResultPrinter { |
325 |
+ |
PithyResultPrinter(java.io.PrintStream writer) { super(writer); } |
326 |
+ |
long runTime; |
327 |
+ |
public void startTest(Test test) {} |
328 |
+ |
protected void printHeader(long runTime) { |
329 |
+ |
this.runTime = runTime; // defer printing for later |
330 |
+ |
} |
331 |
+ |
protected void printFooter(TestResult result) { |
332 |
+ |
if (result.wasSuccessful()) { |
333 |
+ |
getWriter().println("OK (" + result.runCount() + " tests)" |
334 |
+ |
+ " Time: " + elapsedTimeAsString(runTime)); |
335 |
+ |
} else { |
336 |
+ |
getWriter().println("Time: " + elapsedTimeAsString(runTime)); |
337 |
+ |
super.printFooter(result); |
338 |
+ |
} |
339 |
+ |
} |
340 |
+ |
} |
341 |
+ |
|
342 |
+ |
/** |
343 |
+ |
* Returns a TestRunner that doesn't bother with unnecessary |
344 |
+ |
* fluff, like printing a "." for each test case. |
345 |
+ |
*/ |
346 |
+ |
static junit.textui.TestRunner newPithyTestRunner() { |
347 |
+ |
junit.textui.TestRunner runner = new junit.textui.TestRunner(); |
348 |
+ |
runner.setPrinter(new PithyResultPrinter(System.out)); |
349 |
+ |
return runner; |
350 |
+ |
} |
351 |
+ |
|
352 |
|
/** |
353 |
|
* Runs all unit tests in the given test suite. |
354 |
|
* Actual behavior influenced by jsr166.* system properties. |
360 |
|
System.setSecurityManager(new SecurityManager()); |
361 |
|
} |
362 |
|
for (int i = 0; i < suiteRuns; i++) { |
363 |
< |
TestResult result = junit.textui.TestRunner.run(suite); |
363 |
> |
TestResult result = newPithyTestRunner().doRun(suite); |
364 |
|
if (!result.wasSuccessful()) |
365 |
|
System.exit(1); |
366 |
|
System.gc(); |
511 |
|
"LongAdderTest", |
512 |
|
"SplittableRandomTest", |
513 |
|
"StampedLockTest", |
514 |
+ |
"SubmissionPublisherTest", |
515 |
|
"ThreadLocalRandom8Test", |
516 |
+ |
"TimeUnit8Test", |
517 |
|
}; |
518 |
|
addNamedTestClasses(suite, java8TestClassNames); |
519 |
|
} |
521 |
|
// Java9+ test classes |
522 |
|
if (atLeastJava9()) { |
523 |
|
String[] java9TestClassNames = { |
524 |
< |
// Currently empty |
524 |
> |
"AtomicBoolean9Test", |
525 |
> |
"AtomicInteger9Test", |
526 |
> |
"AtomicIntegerArray9Test", |
527 |
> |
"AtomicLong9Test", |
528 |
> |
"AtomicLongArray9Test", |
529 |
> |
"AtomicReference9Test", |
530 |
> |
"AtomicReferenceArray9Test", |
531 |
> |
"ExecutorCompletionService9Test", |
532 |
|
}; |
533 |
|
addNamedTestClasses(suite, java9TestClassNames); |
534 |
|
} |
595 |
|
} else { |
596 |
|
return new TestSuite(); |
597 |
|
} |
457 |
– |
|
598 |
|
} |
599 |
|
|
600 |
|
// Delays for timing-dependent tests, in milliseconds. |
605 |
|
public static long LONG_DELAY_MS; |
606 |
|
|
607 |
|
/** |
608 |
< |
* Returns the shortest timed delay. This could |
609 |
< |
* be reimplemented to use for example a Property. |
608 |
> |
* Returns the shortest timed delay. This can be scaled up for |
609 |
> |
* slow machines using the jsr166.delay.factor system property, |
610 |
> |
* or via jtreg's -timeoutFactor: flag. |
611 |
> |
* http://openjdk.java.net/jtreg/command-help.html |
612 |
|
*/ |
613 |
|
protected long getShortDelay() { |
614 |
< |
return 50; |
614 |
> |
return (long) (50 * delayFactor); |
615 |
|
} |
616 |
|
|
617 |
|
/** |
654 |
|
* the same test have no effect. |
655 |
|
*/ |
656 |
|
public void threadRecordFailure(Throwable t) { |
657 |
+ |
System.err.println(t); |
658 |
+ |
dumpTestThreads(); |
659 |
|
threadFailure.compareAndSet(null, t); |
660 |
|
} |
661 |
|
|
663 |
|
setDelays(); |
664 |
|
} |
665 |
|
|
666 |
+ |
void tearDownFail(String format, Object... args) { |
667 |
+ |
String msg = toString() + ": " + String.format(format, args); |
668 |
+ |
System.err.println(msg); |
669 |
+ |
dumpTestThreads(); |
670 |
+ |
throw new AssertionFailedError(msg); |
671 |
+ |
} |
672 |
+ |
|
673 |
|
/** |
674 |
|
* Extra checks that get done for all test cases. |
675 |
|
* |
697 |
|
} |
698 |
|
|
699 |
|
if (Thread.interrupted()) |
700 |
< |
throw new AssertionFailedError("interrupt status set in main thread"); |
700 |
> |
tearDownFail("interrupt status set in main thread"); |
701 |
|
|
702 |
|
checkForkJoinPoolThreadLeaks(); |
703 |
|
} |
704 |
|
|
705 |
|
/** |
706 |
< |
* Finds missing try { ... } finally { joinPool(e); } |
706 |
> |
* Finds missing PoolCleaners |
707 |
|
*/ |
708 |
|
void checkForkJoinPoolThreadLeaks() throws InterruptedException { |
709 |
< |
Thread[] survivors = new Thread[5]; |
709 |
> |
Thread[] survivors = new Thread[7]; |
710 |
|
int count = Thread.enumerate(survivors); |
711 |
|
for (int i = 0; i < count; i++) { |
712 |
|
Thread thread = survivors[i]; |
714 |
|
if (name.startsWith("ForkJoinPool-")) { |
715 |
|
// give thread some time to terminate |
716 |
|
thread.join(LONG_DELAY_MS); |
717 |
< |
if (!thread.isAlive()) continue; |
718 |
< |
throw new AssertionFailedError |
719 |
< |
(String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n", |
569 |
< |
toString(), name)); |
717 |
> |
if (thread.isAlive()) |
718 |
> |
tearDownFail("Found leaked ForkJoinPool thread thread=%s", |
719 |
> |
thread); |
720 |
|
} |
721 |
|
} |
722 |
+ |
|
723 |
+ |
if (!ForkJoinPool.commonPool() |
724 |
+ |
.awaitQuiescence(LONG_DELAY_MS, MILLISECONDS)) |
725 |
+ |
tearDownFail("ForkJoin common pool thread stuck"); |
726 |
|
} |
727 |
|
|
728 |
|
/** |
735 |
|
fail(reason); |
736 |
|
} catch (AssertionFailedError t) { |
737 |
|
threadRecordFailure(t); |
738 |
< |
fail(reason); |
738 |
> |
throw t; |
739 |
|
} |
740 |
|
} |
741 |
|
|
862 |
|
/** |
863 |
|
* Delays, via Thread.sleep, for the given millisecond delay, but |
864 |
|
* if the sleep is shorter than specified, may re-sleep or yield |
865 |
< |
* until time elapses. |
865 |
> |
* until time elapses. Ensures that the given time, as measured |
866 |
> |
* by System.nanoTime(), has elapsed. |
867 |
|
*/ |
868 |
|
static void delay(long millis) throws InterruptedException { |
869 |
< |
long startTime = System.nanoTime(); |
870 |
< |
long ns = millis * 1000 * 1000; |
871 |
< |
for (;;) { |
869 |
> |
long nanos = millis * (1000 * 1000); |
870 |
> |
final long wakeupTime = System.nanoTime() + nanos; |
871 |
> |
do { |
872 |
|
if (millis > 0L) |
873 |
|
Thread.sleep(millis); |
874 |
|
else // too short to sleep |
875 |
|
Thread.yield(); |
876 |
< |
long d = ns - (System.nanoTime() - startTime); |
877 |
< |
if (d > 0L) |
878 |
< |
millis = d / (1000 * 1000); |
879 |
< |
else |
880 |
< |
break; |
876 |
> |
nanos = wakeupTime - System.nanoTime(); |
877 |
> |
millis = nanos / (1000 * 1000); |
878 |
> |
} while (nanos >= 0L); |
879 |
> |
} |
880 |
> |
|
881 |
> |
/** |
882 |
> |
* Allows use of try-with-resources with per-test thread pools. |
883 |
> |
*/ |
884 |
> |
class PoolCleaner implements AutoCloseable { |
885 |
> |
private final ExecutorService pool; |
886 |
> |
public PoolCleaner(ExecutorService pool) { this.pool = pool; } |
887 |
> |
public void close() { joinPool(pool); } |
888 |
> |
} |
889 |
> |
|
890 |
> |
/** |
891 |
> |
* An extension of PoolCleaner that has an action to release the pool. |
892 |
> |
*/ |
893 |
> |
class PoolCleanerWithReleaser extends PoolCleaner { |
894 |
> |
private final Runnable releaser; |
895 |
> |
public PoolCleanerWithReleaser(ExecutorService pool, Runnable releaser) { |
896 |
> |
super(pool); |
897 |
> |
this.releaser = releaser; |
898 |
> |
} |
899 |
> |
public void close() { |
900 |
> |
try { |
901 |
> |
releaser.run(); |
902 |
> |
} finally { |
903 |
> |
super.close(); |
904 |
> |
} |
905 |
|
} |
906 |
|
} |
907 |
|
|
908 |
+ |
PoolCleaner cleaner(ExecutorService pool) { |
909 |
+ |
return new PoolCleaner(pool); |
910 |
+ |
} |
911 |
+ |
|
912 |
+ |
PoolCleaner cleaner(ExecutorService pool, Runnable releaser) { |
913 |
+ |
return new PoolCleanerWithReleaser(pool, releaser); |
914 |
+ |
} |
915 |
+ |
|
916 |
+ |
PoolCleaner cleaner(ExecutorService pool, CountDownLatch latch) { |
917 |
+ |
return new PoolCleanerWithReleaser(pool, releaser(latch)); |
918 |
+ |
} |
919 |
+ |
|
920 |
+ |
Runnable releaser(final CountDownLatch latch) { |
921 |
+ |
return new Runnable() { public void run() { |
922 |
+ |
do { latch.countDown(); } |
923 |
+ |
while (latch.getCount() > 0); |
924 |
+ |
}}; |
925 |
+ |
} |
926 |
+ |
|
927 |
+ |
PoolCleaner cleaner(ExecutorService pool, AtomicBoolean flag) { |
928 |
+ |
return new PoolCleanerWithReleaser(pool, releaser(flag)); |
929 |
+ |
} |
930 |
+ |
|
931 |
+ |
Runnable releaser(final AtomicBoolean flag) { |
932 |
+ |
return new Runnable() { public void run() { flag.set(true); }}; |
933 |
+ |
} |
934 |
+ |
|
935 |
|
/** |
936 |
|
* Waits out termination of a thread pool or fails doing so. |
937 |
|
*/ |
938 |
|
void joinPool(ExecutorService pool) { |
939 |
|
try { |
940 |
|
pool.shutdown(); |
941 |
< |
if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS)) |
942 |
< |
fail("ExecutorService " + pool + |
943 |
< |
" did not terminate in a timely manner"); |
941 |
> |
if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS)) { |
942 |
> |
try { |
943 |
> |
threadFail("ExecutorService " + pool + |
944 |
> |
" did not terminate in a timely manner"); |
945 |
> |
} finally { |
946 |
> |
// last resort, for the benefit of subsequent tests |
947 |
> |
pool.shutdownNow(); |
948 |
> |
pool.awaitTermination(MEDIUM_DELAY_MS, MILLISECONDS); |
949 |
> |
} |
950 |
> |
} |
951 |
|
} catch (SecurityException ok) { |
952 |
|
// Allowed in case test doesn't have privs |
953 |
|
} catch (InterruptedException fail) { |
954 |
< |
fail("Unexpected InterruptedException"); |
954 |
> |
threadFail("Unexpected InterruptedException"); |
955 |
|
} |
956 |
|
} |
957 |
|
|
958 |
|
/** Like Runnable, but with the freedom to throw anything */ |
959 |
< |
interface Thunk { public void run() throws Throwable; } |
959 |
> |
interface Action { public void run() throws Throwable; } |
960 |
|
|
961 |
|
/** |
962 |
< |
* Runs all the given tasks in parallel, failing if any fail. |
962 |
> |
* Runs all the given actions in parallel, failing if any fail. |
963 |
|
* Useful for running multiple variants of tests that are |
964 |
|
* necessarily individually slow because they must block. |
965 |
|
*/ |
966 |
< |
void testInParallel(Thunk ... thunks) { |
966 |
> |
void testInParallel(Action ... actions) { |
967 |
|
ExecutorService pool = Executors.newCachedThreadPool(); |
968 |
< |
try { |
969 |
< |
ArrayList<Future<?>> futures = new ArrayList<>(thunks.length); |
970 |
< |
for (final Thunk thunk : thunks) |
968 |
> |
try (PoolCleaner cleaner = cleaner(pool)) { |
969 |
> |
ArrayList<Future<?>> futures = new ArrayList<>(actions.length); |
970 |
> |
for (final Action action : actions) |
971 |
|
futures.add(pool.submit(new CheckedRunnable() { |
972 |
< |
public void realRun() throws Throwable { thunk.run();}})); |
972 |
> |
public void realRun() throws Throwable { action.run();}})); |
973 |
|
for (Future<?> future : futures) |
974 |
|
try { |
975 |
|
assertNull(future.get(LONG_DELAY_MS, MILLISECONDS)); |
978 |
|
} catch (Exception ex) { |
979 |
|
threadUnexpectedException(ex); |
980 |
|
} |
768 |
– |
} finally { |
769 |
– |
joinPool(pool); |
981 |
|
} |
982 |
|
} |
983 |
|
|
984 |
|
/** |
985 |
< |
* A debugging tool to print all stack traces, as jstack does. |
985 |
> |
* A debugging tool to print stack traces of most threads, as jstack does. |
986 |
> |
* Uninteresting threads are filtered out. |
987 |
|
*/ |
988 |
< |
static void printAllStackTraces() { |
989 |
< |
for (ThreadInfo info : |
990 |
< |
ManagementFactory.getThreadMXBean() |
991 |
< |
.dumpAllThreads(true, true)) |
988 |
> |
static void dumpTestThreads() { |
989 |
> |
SecurityManager sm = System.getSecurityManager(); |
990 |
> |
if (sm != null) { |
991 |
> |
try { |
992 |
> |
System.setSecurityManager(null); |
993 |
> |
} catch (SecurityException giveUp) { |
994 |
> |
return; |
995 |
> |
} |
996 |
> |
} |
997 |
> |
|
998 |
> |
ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); |
999 |
> |
System.err.println("------ stacktrace dump start ------"); |
1000 |
> |
for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) { |
1001 |
> |
String name = info.getThreadName(); |
1002 |
> |
if ("Signal Dispatcher".equals(name)) |
1003 |
> |
continue; |
1004 |
> |
if ("Reference Handler".equals(name) |
1005 |
> |
&& info.getLockName().startsWith("java.lang.ref.Reference$Lock")) |
1006 |
> |
continue; |
1007 |
> |
if ("Finalizer".equals(name) |
1008 |
> |
&& info.getLockName().startsWith("java.lang.ref.ReferenceQueue$Lock")) |
1009 |
> |
continue; |
1010 |
> |
if ("checkForWedgedTest".equals(name)) |
1011 |
> |
continue; |
1012 |
|
System.err.print(info); |
1013 |
+ |
} |
1014 |
+ |
System.err.println("------ stacktrace dump end ------"); |
1015 |
+ |
|
1016 |
+ |
if (sm != null) System.setSecurityManager(sm); |
1017 |
|
} |
1018 |
|
|
1019 |
|
/** |
1033 |
|
delay(millis); |
1034 |
|
assertTrue(thread.isAlive()); |
1035 |
|
} catch (InterruptedException fail) { |
1036 |
< |
fail("Unexpected InterruptedException"); |
1036 |
> |
threadFail("Unexpected InterruptedException"); |
1037 |
|
} |
1038 |
|
} |
1039 |
|
|
1055 |
|
for (Thread thread : threads) |
1056 |
|
assertTrue(thread.isAlive()); |
1057 |
|
} catch (InterruptedException fail) { |
1058 |
< |
fail("Unexpected InterruptedException"); |
1058 |
> |
threadFail("Unexpected InterruptedException"); |
1059 |
|
} |
1060 |
|
} |
1061 |
|
|
1333 |
|
} finally { |
1334 |
|
if (t.getState() != Thread.State.TERMINATED) { |
1335 |
|
t.interrupt(); |
1336 |
< |
fail("Test timed out"); |
1336 |
> |
threadFail("timed out waiting for thread to terminate"); |
1337 |
|
} |
1338 |
|
} |
1339 |
|
} |
1458 |
|
public static final String TEST_STRING = "a test string"; |
1459 |
|
|
1460 |
|
public static class StringTask implements Callable<String> { |
1461 |
< |
public String call() { return TEST_STRING; } |
1461 |
> |
final String value; |
1462 |
> |
public StringTask() { this(TEST_STRING); } |
1463 |
> |
public StringTask(String value) { this.value = value; } |
1464 |
> |
public String call() { return value; } |
1465 |
|
} |
1466 |
|
|
1467 |
|
public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) { |
1474 |
|
}}; |
1475 |
|
} |
1476 |
|
|
1477 |
< |
public Runnable awaiter(final CountDownLatch latch) { |
1477 |
> |
public Runnable countDowner(final CountDownLatch latch) { |
1478 |
|
return new CheckedRunnable() { |
1479 |
|
public void realRun() throws InterruptedException { |
1480 |
< |
await(latch); |
1480 |
> |
latch.countDown(); |
1481 |
|
}}; |
1482 |
|
} |
1483 |
|
|
1484 |
< |
public void await(CountDownLatch latch) { |
1484 |
> |
class LatchAwaiter extends CheckedRunnable { |
1485 |
> |
static final int NEW = 0; |
1486 |
> |
static final int RUNNING = 1; |
1487 |
> |
static final int DONE = 2; |
1488 |
> |
final CountDownLatch latch; |
1489 |
> |
int state = NEW; |
1490 |
> |
LatchAwaiter(CountDownLatch latch) { this.latch = latch; } |
1491 |
> |
public void realRun() throws InterruptedException { |
1492 |
> |
state = 1; |
1493 |
> |
await(latch); |
1494 |
> |
state = 2; |
1495 |
> |
} |
1496 |
> |
} |
1497 |
> |
|
1498 |
> |
public LatchAwaiter awaiter(CountDownLatch latch) { |
1499 |
> |
return new LatchAwaiter(latch); |
1500 |
> |
} |
1501 |
> |
|
1502 |
> |
public void await(CountDownLatch latch, long timeoutMillis) { |
1503 |
|
try { |
1504 |
< |
assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS)); |
1504 |
> |
if (!latch.await(timeoutMillis, MILLISECONDS)) |
1505 |
> |
fail("timed out waiting for CountDownLatch for " |
1506 |
> |
+ (timeoutMillis/1000) + " sec"); |
1507 |
|
} catch (Throwable fail) { |
1508 |
|
threadUnexpectedException(fail); |
1509 |
|
} |
1510 |
|
} |
1511 |
|
|
1512 |
+ |
public void await(CountDownLatch latch) { |
1513 |
+ |
await(latch, LONG_DELAY_MS); |
1514 |
+ |
} |
1515 |
+ |
|
1516 |
|
public void await(Semaphore semaphore) { |
1517 |
|
try { |
1518 |
< |
assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS)); |
1518 |
> |
if (!semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS)) |
1519 |
> |
fail("timed out waiting for Semaphore for " |
1520 |
> |
+ (LONG_DELAY_MS/1000) + " sec"); |
1521 |
|
} catch (Throwable fail) { |
1522 |
|
threadUnexpectedException(fail); |
1523 |
|
} |
1853 |
|
} catch (NoSuchElementException success) {} |
1854 |
|
assertFalse(it.hasNext()); |
1855 |
|
} |
1856 |
+ |
|
1857 |
+ |
public <T> Callable<T> callableThrowing(final Exception ex) { |
1858 |
+ |
return new Callable<T>() { public T call() throws Exception { throw ex; }}; |
1859 |
+ |
} |
1860 |
+ |
|
1861 |
+ |
public Runnable runnableThrowing(final RuntimeException ex) { |
1862 |
+ |
return new Runnable() { public void run() { throw ex; }}; |
1863 |
+ |
} |
1864 |
+ |
|
1865 |
+ |
/** A reusable thread pool to be shared by tests. */ |
1866 |
+ |
static final ExecutorService cachedThreadPool = |
1867 |
+ |
new ThreadPoolExecutor(0, Integer.MAX_VALUE, |
1868 |
+ |
1000L, MILLISECONDS, |
1869 |
+ |
new SynchronousQueue<Runnable>()); |
1870 |
+ |
|
1871 |
|
} |