6 |
|
* Pat Fisher, Mike Judd. |
7 |
|
*/ |
8 |
|
|
9 |
+ |
/* |
10 |
+ |
* @test |
11 |
+ |
* @summary JSR-166 tck tests (conformance testing mode) |
12 |
+ |
* @build * |
13 |
+ |
* @modules java.management |
14 |
+ |
* @run junit/othervm/timeout=1000 JSR166TestCase |
15 |
+ |
*/ |
16 |
+ |
|
17 |
+ |
/* |
18 |
+ |
* @test |
19 |
+ |
* @summary JSR-166 tck tests (whitebox tests allowed) |
20 |
+ |
* @build * |
21 |
+ |
* @modules java.base/java.util.concurrent:open |
22 |
+ |
* java.management |
23 |
+ |
* @run junit/othervm/timeout=1000 |
24 |
+ |
* -Djsr166.testImplementationDetails=true |
25 |
+ |
* JSR166TestCase |
26 |
+ |
* @run junit/othervm/timeout=1000 |
27 |
+ |
* -Djsr166.testImplementationDetails=true |
28 |
+ |
* -Djava.util.concurrent.ForkJoinPool.common.parallelism=0 |
29 |
+ |
* JSR166TestCase |
30 |
+ |
* @run junit/othervm/timeout=1000 |
31 |
+ |
* -Djsr166.testImplementationDetails=true |
32 |
+ |
* -Djava.util.concurrent.ForkJoinPool.common.parallelism=1 |
33 |
+ |
* -Djava.util.secureRandomSeed=true |
34 |
+ |
* JSR166TestCase |
35 |
+ |
*/ |
36 |
+ |
|
37 |
|
import static java.util.concurrent.TimeUnit.MILLISECONDS; |
38 |
+ |
import static java.util.concurrent.TimeUnit.MINUTES; |
39 |
|
import static java.util.concurrent.TimeUnit.NANOSECONDS; |
40 |
|
|
41 |
|
import java.io.ByteArrayInputStream; |
44 |
|
import java.io.ObjectOutputStream; |
45 |
|
import java.lang.management.ManagementFactory; |
46 |
|
import java.lang.management.ThreadInfo; |
47 |
+ |
import java.lang.management.ThreadMXBean; |
48 |
|
import java.lang.reflect.Constructor; |
49 |
|
import java.lang.reflect.Method; |
50 |
|
import java.lang.reflect.Modifier; |
51 |
+ |
import java.nio.file.Files; |
52 |
+ |
import java.nio.file.Paths; |
53 |
|
import java.security.CodeSource; |
54 |
|
import java.security.Permission; |
55 |
|
import java.security.PermissionCollection; |
59 |
|
import java.security.SecurityPermission; |
60 |
|
import java.util.ArrayList; |
61 |
|
import java.util.Arrays; |
62 |
+ |
import java.util.Collection; |
63 |
+ |
import java.util.Collections; |
64 |
|
import java.util.Date; |
65 |
|
import java.util.Enumeration; |
66 |
|
import java.util.Iterator; |
71 |
|
import java.util.concurrent.Callable; |
72 |
|
import java.util.concurrent.CountDownLatch; |
73 |
|
import java.util.concurrent.CyclicBarrier; |
74 |
+ |
import java.util.concurrent.ExecutionException; |
75 |
+ |
import java.util.concurrent.Executors; |
76 |
|
import java.util.concurrent.ExecutorService; |
77 |
+ |
import java.util.concurrent.ForkJoinPool; |
78 |
|
import java.util.concurrent.Future; |
79 |
|
import java.util.concurrent.RecursiveAction; |
80 |
|
import java.util.concurrent.RecursiveTask; |
81 |
|
import java.util.concurrent.RejectedExecutionHandler; |
82 |
|
import java.util.concurrent.Semaphore; |
83 |
+ |
import java.util.concurrent.SynchronousQueue; |
84 |
|
import java.util.concurrent.ThreadFactory; |
85 |
+ |
import java.util.concurrent.ThreadLocalRandom; |
86 |
|
import java.util.concurrent.ThreadPoolExecutor; |
87 |
|
import java.util.concurrent.TimeoutException; |
88 |
+ |
import java.util.concurrent.atomic.AtomicBoolean; |
89 |
|
import java.util.concurrent.atomic.AtomicReference; |
90 |
+ |
import java.util.regex.Matcher; |
91 |
|
import java.util.regex.Pattern; |
92 |
|
|
93 |
|
import junit.framework.AssertionFailedError; |
106 |
|
* |
107 |
|
* <ol> |
108 |
|
* |
109 |
< |
* <li> All assertions in code running in generated threads must use |
109 |
> |
* <li>All assertions in code running in generated threads must use |
110 |
|
* the forms {@link #threadFail}, {@link #threadAssertTrue}, {@link |
111 |
|
* #threadAssertEquals}, or {@link #threadAssertNull}, (not |
112 |
|
* {@code fail}, {@code assertTrue}, etc.) It is OK (but not |
113 |
|
* particularly recommended) for other code to use these forms too. |
114 |
|
* Only the most typically used JUnit assertion methods are defined |
115 |
< |
* this way, but enough to live with.</li> |
115 |
> |
* this way, but enough to live with. |
116 |
|
* |
117 |
< |
* <li> If you override {@link #setUp} or {@link #tearDown}, make sure |
117 |
> |
* <li>If you override {@link #setUp} or {@link #tearDown}, make sure |
118 |
|
* to invoke {@code super.setUp} and {@code super.tearDown} within |
119 |
|
* them. These methods are used to clear and check for thread |
120 |
< |
* assertion failures.</li> |
120 |
> |
* assertion failures. |
121 |
|
* |
122 |
|
* <li>All delays and timeouts must use one of the constants {@code |
123 |
|
* SHORT_DELAY_MS}, {@code SMALL_DELAY_MS}, {@code MEDIUM_DELAY_MS}, |
128 |
|
* is always discriminable as larger than SHORT and smaller than |
129 |
|
* MEDIUM. And so on. These constants are set to conservative values, |
130 |
|
* but even so, if there is ever any doubt, they can all be increased |
131 |
< |
* in one spot to rerun tests on slower platforms.</li> |
131 |
> |
* in one spot to rerun tests on slower platforms. |
132 |
|
* |
133 |
< |
* <li> All threads generated must be joined inside each test case |
133 |
> |
* <li>All threads generated must be joined inside each test case |
134 |
|
* method (or {@code fail} to do so) before returning from the |
135 |
|
* method. The {@code joinPool} method can be used to do this when |
136 |
< |
* using Executors.</li> |
136 |
> |
* using Executors. |
137 |
|
* |
138 |
|
* </ol> |
139 |
|
* |
140 |
|
* <p><b>Other notes</b> |
141 |
|
* <ul> |
142 |
|
* |
143 |
< |
* <li> Usually, there is one testcase method per JSR166 method |
143 |
> |
* <li>Usually, there is one testcase method per JSR166 method |
144 |
|
* covering "normal" operation, and then as many exception-testing |
145 |
|
* methods as there are exceptions the method can throw. Sometimes |
146 |
|
* there are multiple tests per JSR166 method when the different |
147 |
|
* "normal" behaviors differ significantly. And sometimes testcases |
148 |
< |
* cover multiple methods when they cannot be tested in |
108 |
< |
* isolation.</li> |
148 |
> |
* cover multiple methods when they cannot be tested in isolation. |
149 |
|
* |
150 |
< |
* <li> The documentation style for testcases is to provide as javadoc |
150 |
> |
* <li>The documentation style for testcases is to provide as javadoc |
151 |
|
* a simple sentence or two describing the property that the testcase |
152 |
|
* method purports to test. The javadocs do not say anything about how |
153 |
< |
* the property is tested. To find out, read the code.</li> |
153 |
> |
* the property is tested. To find out, read the code. |
154 |
|
* |
155 |
< |
* <li> These tests are "conformance tests", and do not attempt to |
155 |
> |
* <li>These tests are "conformance tests", and do not attempt to |
156 |
|
* test throughput, latency, scalability or other performance factors |
157 |
|
* (see the separate "jtreg" tests for a set intended to check these |
158 |
|
* for the most central aspects of functionality.) So, most tests use |
159 |
|
* the smallest sensible numbers of threads, collection sizes, etc |
160 |
< |
* needed to check basic conformance.</li> |
160 |
> |
* needed to check basic conformance. |
161 |
|
* |
162 |
|
* <li>The test classes currently do not declare inclusion in |
163 |
|
* any particular package to simplify things for people integrating |
164 |
< |
* them in TCK test suites.</li> |
164 |
> |
* them in TCK test suites. |
165 |
|
* |
166 |
< |
* <li> As a convenience, the {@code main} of this class (JSR166TestCase) |
167 |
< |
* runs all JSR166 unit tests.</li> |
166 |
> |
* <li>As a convenience, the {@code main} of this class (JSR166TestCase) |
167 |
> |
* runs all JSR166 unit tests. |
168 |
|
* |
169 |
|
* </ul> |
170 |
|
*/ |
208 |
|
private static final int suiteRuns = |
209 |
|
Integer.getInteger("jsr166.suiteRuns", 1); |
210 |
|
|
211 |
+ |
/** |
212 |
+ |
* Returns the value of the system property, or NaN if not defined. |
213 |
+ |
*/ |
214 |
+ |
private static float systemPropertyValue(String name) { |
215 |
+ |
String floatString = System.getProperty(name); |
216 |
+ |
if (floatString == null) |
217 |
+ |
return Float.NaN; |
218 |
+ |
try { |
219 |
+ |
return Float.parseFloat(floatString); |
220 |
+ |
} catch (NumberFormatException ex) { |
221 |
+ |
throw new IllegalArgumentException( |
222 |
+ |
String.format("Bad float value in system property %s=%s", |
223 |
+ |
name, floatString)); |
224 |
+ |
} |
225 |
+ |
} |
226 |
+ |
|
227 |
+ |
/** |
228 |
+ |
* The scaling factor to apply to standard delays used in tests. |
229 |
+ |
* May be initialized from any of: |
230 |
+ |
* - the "jsr166.delay.factor" system property |
231 |
+ |
* - the "test.timeout.factor" system property (as used by jtreg) |
232 |
+ |
* See: http://openjdk.java.net/jtreg/tag-spec.html |
233 |
+ |
* - hard-coded fuzz factor when using a known slowpoke VM |
234 |
+ |
*/ |
235 |
+ |
private static final float delayFactor = delayFactor(); |
236 |
+ |
|
237 |
+ |
private static float delayFactor() { |
238 |
+ |
float x; |
239 |
+ |
if (!Float.isNaN(x = systemPropertyValue("jsr166.delay.factor"))) |
240 |
+ |
return x; |
241 |
+ |
if (!Float.isNaN(x = systemPropertyValue("test.timeout.factor"))) |
242 |
+ |
return x; |
243 |
+ |
String prop = System.getProperty("java.vm.version"); |
244 |
+ |
if (prop != null && prop.matches(".*debug.*")) |
245 |
+ |
return 4.0f; // How much slower is fastdebug than product?! |
246 |
+ |
return 1.0f; |
247 |
+ |
} |
248 |
+ |
|
249 |
|
public JSR166TestCase() { super(); } |
250 |
|
public JSR166TestCase(String name) { super(name); } |
251 |
|
|
261 |
|
return (regex == null) ? null : Pattern.compile(regex); |
262 |
|
} |
263 |
|
|
264 |
< |
protected void runTest() throws Throwable { |
264 |
> |
// Instrumentation to debug very rare, but very annoying hung test runs. |
265 |
> |
static volatile TestCase currentTestCase; |
266 |
> |
// static volatile int currentRun = 0; |
267 |
> |
static { |
268 |
> |
Runnable checkForWedgedTest = new Runnable() { public void run() { |
269 |
> |
// Avoid spurious reports with enormous runsPerTest. |
270 |
> |
// A single test case run should never take more than 1 second. |
271 |
> |
// But let's cap it at the high end too ... |
272 |
> |
final int timeoutMinutes = |
273 |
> |
Math.min(15, Math.max(runsPerTest / 60, 1)); |
274 |
> |
for (TestCase lastTestCase = currentTestCase;;) { |
275 |
> |
try { MINUTES.sleep(timeoutMinutes); } |
276 |
> |
catch (InterruptedException unexpected) { break; } |
277 |
> |
if (lastTestCase == currentTestCase) { |
278 |
> |
System.err.printf( |
279 |
> |
"Looks like we're stuck running test: %s%n", |
280 |
> |
lastTestCase); |
281 |
> |
// System.err.printf( |
282 |
> |
// "Looks like we're stuck running test: %s (%d/%d)%n", |
283 |
> |
// lastTestCase, currentRun, runsPerTest); |
284 |
> |
// System.err.println("availableProcessors=" + |
285 |
> |
// Runtime.getRuntime().availableProcessors()); |
286 |
> |
// System.err.printf("cpu model = %s%n", cpuModel()); |
287 |
> |
dumpTestThreads(); |
288 |
> |
// one stack dump is probably enough; more would be spam |
289 |
> |
break; |
290 |
> |
} |
291 |
> |
lastTestCase = currentTestCase; |
292 |
> |
}}}; |
293 |
> |
Thread thread = new Thread(checkForWedgedTest, "checkForWedgedTest"); |
294 |
> |
thread.setDaemon(true); |
295 |
> |
thread.start(); |
296 |
> |
} |
297 |
> |
|
298 |
> |
// public static String cpuModel() { |
299 |
> |
// try { |
300 |
> |
// Matcher matcher = Pattern.compile("model name\\s*: (.*)") |
301 |
> |
// .matcher(new String( |
302 |
> |
// Files.readAllBytes(Paths.get("/proc/cpuinfo")), "UTF-8")); |
303 |
> |
// matcher.find(); |
304 |
> |
// return matcher.group(1); |
305 |
> |
// } catch (Exception ex) { return null; } |
306 |
> |
// } |
307 |
> |
|
308 |
> |
public void runBare() throws Throwable { |
309 |
> |
currentTestCase = this; |
310 |
|
if (methodFilter == null |
311 |
< |
|| methodFilter.matcher(toString()).find()) { |
312 |
< |
for (int i = 0; i < runsPerTest; i++) { |
313 |
< |
if (profileTests) |
314 |
< |
runTestProfiled(); |
315 |
< |
else |
316 |
< |
super.runTest(); |
317 |
< |
} |
311 |
> |
|| methodFilter.matcher(toString()).find()) |
312 |
> |
super.runBare(); |
313 |
> |
} |
314 |
> |
|
315 |
> |
protected void runTest() throws Throwable { |
316 |
> |
for (int i = 0; i < runsPerTest; i++) { |
317 |
> |
// currentRun = i; |
318 |
> |
if (profileTests) |
319 |
> |
runTestProfiled(); |
320 |
> |
else |
321 |
> |
super.runTest(); |
322 |
|
} |
323 |
|
} |
324 |
|
|
325 |
|
protected void runTestProfiled() throws Throwable { |
326 |
< |
// Warmup run, notably to trigger all needed classloading. |
327 |
< |
super.runTest(); |
201 |
< |
long t0 = System.nanoTime(); |
202 |
< |
try { |
326 |
> |
for (int i = 0; i < 2; i++) { |
327 |
> |
long startTime = System.nanoTime(); |
328 |
|
super.runTest(); |
329 |
< |
} finally { |
330 |
< |
long elapsedMillis = millisElapsedSince(t0); |
331 |
< |
if (elapsedMillis >= profileThreshold) |
329 |
> |
long elapsedMillis = millisElapsedSince(startTime); |
330 |
> |
if (elapsedMillis < profileThreshold) |
331 |
> |
break; |
332 |
> |
// Never report first run of any test; treat it as a |
333 |
> |
// warmup run, notably to trigger all needed classloading, |
334 |
> |
if (i > 0) |
335 |
|
System.out.printf("%n%s: %d%n", toString(), elapsedMillis); |
336 |
|
} |
337 |
|
} |
343 |
|
main(suite(), args); |
344 |
|
} |
345 |
|
|
346 |
+ |
static class PithyResultPrinter extends junit.textui.ResultPrinter { |
347 |
+ |
PithyResultPrinter(java.io.PrintStream writer) { super(writer); } |
348 |
+ |
long runTime; |
349 |
+ |
public void startTest(Test test) {} |
350 |
+ |
protected void printHeader(long runTime) { |
351 |
+ |
this.runTime = runTime; // defer printing for later |
352 |
+ |
} |
353 |
+ |
protected void printFooter(TestResult result) { |
354 |
+ |
if (result.wasSuccessful()) { |
355 |
+ |
getWriter().println("OK (" + result.runCount() + " tests)" |
356 |
+ |
+ " Time: " + elapsedTimeAsString(runTime)); |
357 |
+ |
} else { |
358 |
+ |
getWriter().println("Time: " + elapsedTimeAsString(runTime)); |
359 |
+ |
super.printFooter(result); |
360 |
+ |
} |
361 |
+ |
} |
362 |
+ |
} |
363 |
+ |
|
364 |
+ |
/** |
365 |
+ |
* Returns a TestRunner that doesn't bother with unnecessary |
366 |
+ |
* fluff, like printing a "." for each test case. |
367 |
+ |
*/ |
368 |
+ |
static junit.textui.TestRunner newPithyTestRunner() { |
369 |
+ |
junit.textui.TestRunner runner = new junit.textui.TestRunner(); |
370 |
+ |
runner.setPrinter(new PithyResultPrinter(System.out)); |
371 |
+ |
return runner; |
372 |
+ |
} |
373 |
+ |
|
374 |
|
/** |
375 |
|
* Runs all unit tests in the given test suite. |
376 |
|
* Actual behavior influenced by jsr166.* system properties. |
382 |
|
System.setSecurityManager(new SecurityManager()); |
383 |
|
} |
384 |
|
for (int i = 0; i < suiteRuns; i++) { |
385 |
< |
TestResult result = junit.textui.TestRunner.run(suite); |
385 |
> |
TestResult result = newPithyTestRunner().doRun(suite); |
386 |
|
if (!result.wasSuccessful()) |
387 |
|
System.exit(1); |
388 |
|
System.gc(); |
437 |
|
public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; } |
438 |
|
public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; } |
439 |
|
public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; } |
440 |
< |
public static boolean atLeastJava9() { return JAVA_CLASS_VERSION >= 53.0; } |
440 |
> |
public static boolean atLeastJava9() { |
441 |
> |
return JAVA_CLASS_VERSION >= 53.0 |
442 |
> |
// As of 2015-09, java9 still uses 52.0 class file version |
443 |
> |
|| JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?(9|[0-9][0-9])$"); |
444 |
> |
} |
445 |
> |
public static boolean atLeastJava10() { |
446 |
> |
return JAVA_CLASS_VERSION >= 54.0 |
447 |
> |
|| JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?[0-9][0-9]$"); |
448 |
> |
} |
449 |
|
|
450 |
|
/** |
451 |
|
* Collects all JSR166 unit tests as one suite. |
466 |
|
AbstractQueuedLongSynchronizerTest.suite(), |
467 |
|
ArrayBlockingQueueTest.suite(), |
468 |
|
ArrayDequeTest.suite(), |
469 |
+ |
ArrayListTest.suite(), |
470 |
|
AtomicBooleanTest.suite(), |
471 |
|
AtomicIntegerArrayTest.suite(), |
472 |
|
AtomicIntegerFieldUpdaterTest.suite(), |
489 |
|
CopyOnWriteArrayListTest.suite(), |
490 |
|
CopyOnWriteArraySetTest.suite(), |
491 |
|
CountDownLatchTest.suite(), |
492 |
+ |
CountedCompleterTest.suite(), |
493 |
|
CyclicBarrierTest.suite(), |
494 |
|
DelayQueueTest.suite(), |
495 |
|
EntryTest.suite(), |
518 |
|
TreeMapTest.suite(), |
519 |
|
TreeSetTest.suite(), |
520 |
|
TreeSubMapTest.suite(), |
521 |
< |
TreeSubSetTest.suite()); |
521 |
> |
TreeSubSetTest.suite(), |
522 |
> |
VectorTest.suite()); |
523 |
|
|
524 |
|
// Java8+ test classes |
525 |
|
if (atLeastJava8()) { |
526 |
|
String[] java8TestClassNames = { |
527 |
+ |
"ArrayDeque8Test", |
528 |
|
"Atomic8Test", |
529 |
|
"CompletableFutureTest", |
530 |
|
"ConcurrentHashMap8Test", |
531 |
< |
"CountedCompleterTest", |
531 |
> |
"CountedCompleter8Test", |
532 |
|
"DoubleAccumulatorTest", |
533 |
|
"DoubleAdderTest", |
534 |
|
"ForkJoinPool8Test", |
535 |
|
"ForkJoinTask8Test", |
536 |
+ |
"LinkedBlockingDeque8Test", |
537 |
+ |
"LinkedBlockingQueue8Test", |
538 |
|
"LongAccumulatorTest", |
539 |
|
"LongAdderTest", |
540 |
|
"SplittableRandomTest", |
541 |
|
"StampedLockTest", |
542 |
+ |
"SubmissionPublisherTest", |
543 |
|
"ThreadLocalRandom8Test", |
544 |
+ |
"TimeUnit8Test", |
545 |
|
}; |
546 |
|
addNamedTestClasses(suite, java8TestClassNames); |
547 |
|
} |
549 |
|
// Java9+ test classes |
550 |
|
if (atLeastJava9()) { |
551 |
|
String[] java9TestClassNames = { |
552 |
< |
"ThreadPoolExecutor9Test", |
552 |
> |
"AtomicBoolean9Test", |
553 |
> |
"AtomicInteger9Test", |
554 |
> |
"AtomicIntegerArray9Test", |
555 |
> |
"AtomicLong9Test", |
556 |
> |
"AtomicLongArray9Test", |
557 |
> |
"AtomicReference9Test", |
558 |
> |
"AtomicReferenceArray9Test", |
559 |
> |
"ExecutorCompletionService9Test", |
560 |
|
}; |
561 |
|
addNamedTestClasses(suite, java9TestClassNames); |
562 |
|
} |
567 |
|
/** Returns list of junit-style test method names in given class. */ |
568 |
|
public static ArrayList<String> testMethodNames(Class<?> testClass) { |
569 |
|
Method[] methods = testClass.getDeclaredMethods(); |
570 |
< |
ArrayList<String> names = new ArrayList<String>(methods.length); |
570 |
> |
ArrayList<String> names = new ArrayList<>(methods.length); |
571 |
|
for (Method method : methods) { |
572 |
|
if (method.getName().startsWith("test") |
573 |
|
&& Modifier.isPublic(method.getModifiers()) |
623 |
|
} else { |
624 |
|
return new TestSuite(); |
625 |
|
} |
447 |
– |
|
626 |
|
} |
627 |
|
|
628 |
|
// Delays for timing-dependent tests, in milliseconds. |
633 |
|
public static long LONG_DELAY_MS; |
634 |
|
|
635 |
|
/** |
636 |
< |
* Returns the shortest timed delay. This could |
637 |
< |
* be reimplemented to use for example a Property. |
636 |
> |
* Returns the shortest timed delay. This can be scaled up for |
637 |
> |
* slow machines using the jsr166.delay.factor system property, |
638 |
> |
* or via jtreg's -timeoutFactor: flag. |
639 |
> |
* http://openjdk.java.net/jtreg/command-help.html |
640 |
|
*/ |
641 |
|
protected long getShortDelay() { |
642 |
< |
return 50; |
642 |
> |
return (long) (50 * delayFactor); |
643 |
|
} |
644 |
|
|
645 |
|
/** |
673 |
|
* The first exception encountered if any threadAssertXXX method fails. |
674 |
|
*/ |
675 |
|
private final AtomicReference<Throwable> threadFailure |
676 |
< |
= new AtomicReference<Throwable>(null); |
676 |
> |
= new AtomicReference<>(null); |
677 |
|
|
678 |
|
/** |
679 |
|
* Records an exception so that it can be rethrown later in the test |
682 |
|
* the same test have no effect. |
683 |
|
*/ |
684 |
|
public void threadRecordFailure(Throwable t) { |
685 |
+ |
System.err.println(t); |
686 |
+ |
dumpTestThreads(); |
687 |
|
threadFailure.compareAndSet(null, t); |
688 |
|
} |
689 |
|
|
691 |
|
setDelays(); |
692 |
|
} |
693 |
|
|
694 |
+ |
void tearDownFail(String format, Object... args) { |
695 |
+ |
String msg = toString() + ": " + String.format(format, args); |
696 |
+ |
System.err.println(msg); |
697 |
+ |
dumpTestThreads(); |
698 |
+ |
throw new AssertionFailedError(msg); |
699 |
+ |
} |
700 |
+ |
|
701 |
|
/** |
702 |
|
* Extra checks that get done for all test cases. |
703 |
|
* |
725 |
|
} |
726 |
|
|
727 |
|
if (Thread.interrupted()) |
728 |
< |
throw new AssertionFailedError("interrupt status set in main thread"); |
728 |
> |
tearDownFail("interrupt status set in main thread"); |
729 |
|
|
730 |
|
checkForkJoinPoolThreadLeaks(); |
731 |
|
} |
732 |
|
|
733 |
|
/** |
734 |
< |
* Finds missing try { ... } finally { joinPool(e); } |
734 |
> |
* Finds missing PoolCleaners |
735 |
|
*/ |
736 |
|
void checkForkJoinPoolThreadLeaks() throws InterruptedException { |
737 |
< |
Thread[] survivors = new Thread[5]; |
737 |
> |
Thread[] survivors = new Thread[7]; |
738 |
|
int count = Thread.enumerate(survivors); |
739 |
|
for (int i = 0; i < count; i++) { |
740 |
|
Thread thread = survivors[i]; |
742 |
|
if (name.startsWith("ForkJoinPool-")) { |
743 |
|
// give thread some time to terminate |
744 |
|
thread.join(LONG_DELAY_MS); |
745 |
< |
if (!thread.isAlive()) continue; |
746 |
< |
throw new AssertionFailedError |
747 |
< |
(String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n", |
559 |
< |
toString(), name)); |
745 |
> |
if (thread.isAlive()) |
746 |
> |
tearDownFail("Found leaked ForkJoinPool thread thread=%s", |
747 |
> |
thread); |
748 |
|
} |
749 |
|
} |
750 |
+ |
|
751 |
+ |
if (!ForkJoinPool.commonPool() |
752 |
+ |
.awaitQuiescence(LONG_DELAY_MS, MILLISECONDS)) |
753 |
+ |
tearDownFail("ForkJoin common pool thread stuck"); |
754 |
|
} |
755 |
|
|
756 |
|
/** |
763 |
|
fail(reason); |
764 |
|
} catch (AssertionFailedError t) { |
765 |
|
threadRecordFailure(t); |
766 |
< |
fail(reason); |
766 |
> |
throw t; |
767 |
|
} |
768 |
|
} |
769 |
|
|
890 |
|
/** |
891 |
|
* Delays, via Thread.sleep, for the given millisecond delay, but |
892 |
|
* if the sleep is shorter than specified, may re-sleep or yield |
893 |
< |
* until time elapses. |
893 |
> |
* until time elapses. Ensures that the given time, as measured |
894 |
> |
* by System.nanoTime(), has elapsed. |
895 |
|
*/ |
896 |
|
static void delay(long millis) throws InterruptedException { |
897 |
< |
long startTime = System.nanoTime(); |
898 |
< |
long ns = millis * 1000 * 1000; |
899 |
< |
for (;;) { |
897 |
> |
long nanos = millis * (1000 * 1000); |
898 |
> |
final long wakeupTime = System.nanoTime() + nanos; |
899 |
> |
do { |
900 |
|
if (millis > 0L) |
901 |
|
Thread.sleep(millis); |
902 |
|
else // too short to sleep |
903 |
|
Thread.yield(); |
904 |
< |
long d = ns - (System.nanoTime() - startTime); |
905 |
< |
if (d > 0L) |
906 |
< |
millis = d / (1000 * 1000); |
907 |
< |
else |
908 |
< |
break; |
904 |
> |
nanos = wakeupTime - System.nanoTime(); |
905 |
> |
millis = nanos / (1000 * 1000); |
906 |
> |
} while (nanos >= 0L); |
907 |
> |
} |
908 |
> |
|
909 |
> |
/** |
910 |
> |
* Allows use of try-with-resources with per-test thread pools. |
911 |
> |
*/ |
912 |
> |
class PoolCleaner implements AutoCloseable { |
913 |
> |
private final ExecutorService pool; |
914 |
> |
public PoolCleaner(ExecutorService pool) { this.pool = pool; } |
915 |
> |
public void close() { joinPool(pool); } |
916 |
> |
} |
917 |
> |
|
918 |
> |
/** |
919 |
> |
* An extension of PoolCleaner that has an action to release the pool. |
920 |
> |
*/ |
921 |
> |
class PoolCleanerWithReleaser extends PoolCleaner { |
922 |
> |
private final Runnable releaser; |
923 |
> |
public PoolCleanerWithReleaser(ExecutorService pool, Runnable releaser) { |
924 |
> |
super(pool); |
925 |
> |
this.releaser = releaser; |
926 |
|
} |
927 |
+ |
public void close() { |
928 |
+ |
try { |
929 |
+ |
releaser.run(); |
930 |
+ |
} finally { |
931 |
+ |
super.close(); |
932 |
+ |
} |
933 |
+ |
} |
934 |
+ |
} |
935 |
+ |
|
936 |
+ |
PoolCleaner cleaner(ExecutorService pool) { |
937 |
+ |
return new PoolCleaner(pool); |
938 |
+ |
} |
939 |
+ |
|
940 |
+ |
PoolCleaner cleaner(ExecutorService pool, Runnable releaser) { |
941 |
+ |
return new PoolCleanerWithReleaser(pool, releaser); |
942 |
+ |
} |
943 |
+ |
|
944 |
+ |
PoolCleaner cleaner(ExecutorService pool, CountDownLatch latch) { |
945 |
+ |
return new PoolCleanerWithReleaser(pool, releaser(latch)); |
946 |
+ |
} |
947 |
+ |
|
948 |
+ |
Runnable releaser(final CountDownLatch latch) { |
949 |
+ |
return new Runnable() { public void run() { |
950 |
+ |
do { latch.countDown(); } |
951 |
+ |
while (latch.getCount() > 0); |
952 |
+ |
}}; |
953 |
+ |
} |
954 |
+ |
|
955 |
+ |
PoolCleaner cleaner(ExecutorService pool, AtomicBoolean flag) { |
956 |
+ |
return new PoolCleanerWithReleaser(pool, releaser(flag)); |
957 |
+ |
} |
958 |
+ |
|
959 |
+ |
Runnable releaser(final AtomicBoolean flag) { |
960 |
+ |
return new Runnable() { public void run() { flag.set(true); }}; |
961 |
|
} |
962 |
|
|
963 |
|
/** |
964 |
|
* Waits out termination of a thread pool or fails doing so. |
965 |
|
*/ |
966 |
< |
void joinPool(ExecutorService exec) { |
966 |
> |
void joinPool(ExecutorService pool) { |
967 |
|
try { |
968 |
< |
exec.shutdown(); |
969 |
< |
if (!exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS)) |
970 |
< |
fail("ExecutorService " + exec + |
971 |
< |
" did not terminate in a timely manner"); |
968 |
> |
pool.shutdown(); |
969 |
> |
if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS)) { |
970 |
> |
try { |
971 |
> |
threadFail("ExecutorService " + pool + |
972 |
> |
" did not terminate in a timely manner"); |
973 |
> |
} finally { |
974 |
> |
// last resort, for the benefit of subsequent tests |
975 |
> |
pool.shutdownNow(); |
976 |
> |
pool.awaitTermination(MEDIUM_DELAY_MS, MILLISECONDS); |
977 |
> |
} |
978 |
> |
} |
979 |
|
} catch (SecurityException ok) { |
980 |
|
// Allowed in case test doesn't have privs |
981 |
|
} catch (InterruptedException fail) { |
982 |
< |
fail("Unexpected InterruptedException"); |
982 |
> |
threadFail("Unexpected InterruptedException"); |
983 |
> |
} |
984 |
> |
} |
985 |
> |
|
986 |
> |
/** |
987 |
> |
* Like Runnable, but with the freedom to throw anything. |
988 |
> |
* junit folks had the same idea: |
989 |
> |
* http://junit.org/junit5/docs/snapshot/api/org/junit/gen5/api/Executable.html |
990 |
> |
*/ |
991 |
> |
interface Action { public void run() throws Throwable; } |
992 |
> |
|
993 |
> |
/** |
994 |
> |
* Runs all the given actions in parallel, failing if any fail. |
995 |
> |
* Useful for running multiple variants of tests that are |
996 |
> |
* necessarily individually slow because they must block. |
997 |
> |
*/ |
998 |
> |
void testInParallel(Action ... actions) { |
999 |
> |
ExecutorService pool = Executors.newCachedThreadPool(); |
1000 |
> |
try (PoolCleaner cleaner = cleaner(pool)) { |
1001 |
> |
ArrayList<Future<?>> futures = new ArrayList<>(actions.length); |
1002 |
> |
for (final Action action : actions) |
1003 |
> |
futures.add(pool.submit(new CheckedRunnable() { |
1004 |
> |
public void realRun() throws Throwable { action.run();}})); |
1005 |
> |
for (Future<?> future : futures) |
1006 |
> |
try { |
1007 |
> |
assertNull(future.get(LONG_DELAY_MS, MILLISECONDS)); |
1008 |
> |
} catch (ExecutionException ex) { |
1009 |
> |
threadUnexpectedException(ex.getCause()); |
1010 |
> |
} catch (Exception ex) { |
1011 |
> |
threadUnexpectedException(ex); |
1012 |
> |
} |
1013 |
|
} |
1014 |
|
} |
1015 |
|
|
1016 |
|
/** |
1017 |
< |
* A debugging tool to print all stack traces, as jstack does. |
1017 |
> |
* A debugging tool to print stack traces of most threads, as jstack does. |
1018 |
> |
* Uninteresting threads are filtered out. |
1019 |
|
*/ |
1020 |
< |
static void printAllStackTraces() { |
1021 |
< |
for (ThreadInfo info : |
1022 |
< |
ManagementFactory.getThreadMXBean() |
1023 |
< |
.dumpAllThreads(true, true)) |
1020 |
> |
static void dumpTestThreads() { |
1021 |
> |
SecurityManager sm = System.getSecurityManager(); |
1022 |
> |
if (sm != null) { |
1023 |
> |
try { |
1024 |
> |
System.setSecurityManager(null); |
1025 |
> |
} catch (SecurityException giveUp) { |
1026 |
> |
return; |
1027 |
> |
} |
1028 |
> |
} |
1029 |
> |
|
1030 |
> |
ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); |
1031 |
> |
System.err.println("------ stacktrace dump start ------"); |
1032 |
> |
for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) { |
1033 |
> |
final String name = info.getThreadName(); |
1034 |
> |
String lockName; |
1035 |
> |
if ("Signal Dispatcher".equals(name)) |
1036 |
> |
continue; |
1037 |
> |
if ("Reference Handler".equals(name) |
1038 |
> |
&& (lockName = info.getLockName()) != null |
1039 |
> |
&& lockName.startsWith("java.lang.ref.Reference$Lock")) |
1040 |
> |
continue; |
1041 |
> |
if ("Finalizer".equals(name) |
1042 |
> |
&& (lockName = info.getLockName()) != null |
1043 |
> |
&& lockName.startsWith("java.lang.ref.ReferenceQueue$Lock")) |
1044 |
> |
continue; |
1045 |
> |
if ("checkForWedgedTest".equals(name)) |
1046 |
> |
continue; |
1047 |
|
System.err.print(info); |
1048 |
+ |
} |
1049 |
+ |
System.err.println("------ stacktrace dump end ------"); |
1050 |
+ |
|
1051 |
+ |
if (sm != null) System.setSecurityManager(sm); |
1052 |
|
} |
1053 |
|
|
1054 |
|
/** |
1068 |
|
delay(millis); |
1069 |
|
assertTrue(thread.isAlive()); |
1070 |
|
} catch (InterruptedException fail) { |
1071 |
< |
fail("Unexpected InterruptedException"); |
1071 |
> |
threadFail("Unexpected InterruptedException"); |
1072 |
|
} |
1073 |
|
} |
1074 |
|
|
1090 |
|
for (Thread thread : threads) |
1091 |
|
assertTrue(thread.isAlive()); |
1092 |
|
} catch (InterruptedException fail) { |
1093 |
< |
fail("Unexpected InterruptedException"); |
1093 |
> |
threadFail("Unexpected InterruptedException"); |
1094 |
|
} |
1095 |
|
} |
1096 |
|
|
1235 |
|
} |
1236 |
|
public void refresh() {} |
1237 |
|
public String toString() { |
1238 |
< |
List<Permission> ps = new ArrayList<Permission>(); |
1238 |
> |
List<Permission> ps = new ArrayList<>(); |
1239 |
|
for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();) |
1240 |
|
ps.add(e.nextElement()); |
1241 |
|
return "AdjustablePolicy with permissions " + ps; |
1265 |
|
* Sleeps until the given time has elapsed. |
1266 |
|
* Throws AssertionFailedError if interrupted. |
1267 |
|
*/ |
1268 |
< |
void sleep(long millis) { |
1268 |
> |
static void sleep(long millis) { |
1269 |
|
try { |
1270 |
|
delay(millis); |
1271 |
|
} catch (InterruptedException fail) { |
1281 |
|
* thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING. |
1282 |
|
*/ |
1283 |
|
void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) { |
1284 |
< |
long startTime = System.nanoTime(); |
1284 |
> |
long startTime = 0L; |
1285 |
|
for (;;) { |
1286 |
|
Thread.State s = thread.getState(); |
1287 |
|
if (s == Thread.State.BLOCKED || |
1290 |
|
return; |
1291 |
|
else if (s == Thread.State.TERMINATED) |
1292 |
|
fail("Unexpected thread termination"); |
1293 |
+ |
else if (startTime == 0L) |
1294 |
+ |
startTime = System.nanoTime(); |
1295 |
|
else if (millisElapsedSince(startTime) > timeoutMillis) { |
1296 |
|
threadAssertTrue(thread.isAlive()); |
1297 |
|
return; |
1370 |
|
} finally { |
1371 |
|
if (t.getState() != Thread.State.TERMINATED) { |
1372 |
|
t.interrupt(); |
1373 |
< |
fail("Test timed out"); |
1373 |
> |
threadFail("timed out waiting for thread to terminate"); |
1374 |
|
} |
1375 |
|
} |
1376 |
|
} |
1495 |
|
public static final String TEST_STRING = "a test string"; |
1496 |
|
|
1497 |
|
public static class StringTask implements Callable<String> { |
1498 |
< |
public String call() { return TEST_STRING; } |
1498 |
> |
final String value; |
1499 |
> |
public StringTask() { this(TEST_STRING); } |
1500 |
> |
public StringTask(String value) { this.value = value; } |
1501 |
> |
public String call() { return value; } |
1502 |
|
} |
1503 |
|
|
1504 |
|
public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) { |
1511 |
|
}}; |
1512 |
|
} |
1513 |
|
|
1514 |
< |
public Runnable awaiter(final CountDownLatch latch) { |
1514 |
> |
public Runnable countDowner(final CountDownLatch latch) { |
1515 |
|
return new CheckedRunnable() { |
1516 |
|
public void realRun() throws InterruptedException { |
1517 |
< |
await(latch); |
1517 |
> |
latch.countDown(); |
1518 |
|
}}; |
1519 |
|
} |
1520 |
|
|
1521 |
< |
public void await(CountDownLatch latch) { |
1521 |
> |
class LatchAwaiter extends CheckedRunnable { |
1522 |
> |
static final int NEW = 0; |
1523 |
> |
static final int RUNNING = 1; |
1524 |
> |
static final int DONE = 2; |
1525 |
> |
final CountDownLatch latch; |
1526 |
> |
int state = NEW; |
1527 |
> |
LatchAwaiter(CountDownLatch latch) { this.latch = latch; } |
1528 |
> |
public void realRun() throws InterruptedException { |
1529 |
> |
state = 1; |
1530 |
> |
await(latch); |
1531 |
> |
state = 2; |
1532 |
> |
} |
1533 |
> |
} |
1534 |
> |
|
1535 |
> |
public LatchAwaiter awaiter(CountDownLatch latch) { |
1536 |
> |
return new LatchAwaiter(latch); |
1537 |
> |
} |
1538 |
> |
|
1539 |
> |
public void await(CountDownLatch latch, long timeoutMillis) { |
1540 |
|
try { |
1541 |
< |
assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS)); |
1541 |
> |
if (!latch.await(timeoutMillis, MILLISECONDS)) |
1542 |
> |
fail("timed out waiting for CountDownLatch for " |
1543 |
> |
+ (timeoutMillis/1000) + " sec"); |
1544 |
|
} catch (Throwable fail) { |
1545 |
|
threadUnexpectedException(fail); |
1546 |
|
} |
1547 |
|
} |
1548 |
|
|
1549 |
+ |
public void await(CountDownLatch latch) { |
1550 |
+ |
await(latch, LONG_DELAY_MS); |
1551 |
+ |
} |
1552 |
+ |
|
1553 |
|
public void await(Semaphore semaphore) { |
1554 |
|
try { |
1555 |
< |
assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS)); |
1555 |
> |
if (!semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS)) |
1556 |
> |
fail("timed out waiting for Semaphore for " |
1557 |
> |
+ (LONG_DELAY_MS/1000) + " sec"); |
1558 |
|
} catch (Throwable fail) { |
1559 |
|
threadUnexpectedException(fail); |
1560 |
|
} |
1784 |
|
* A CyclicBarrier that uses timed await and fails with |
1785 |
|
* AssertionFailedErrors instead of throwing checked exceptions. |
1786 |
|
*/ |
1787 |
< |
public class CheckedBarrier extends CyclicBarrier { |
1787 |
> |
public static class CheckedBarrier extends CyclicBarrier { |
1788 |
|
public CheckedBarrier(int parties) { super(parties); } |
1789 |
|
|
1790 |
|
public int await() { |
1848 |
|
} |
1849 |
|
} |
1850 |
|
|
1851 |
+ |
void assertImmutable(final Object o) { |
1852 |
+ |
if (o instanceof Collection) { |
1853 |
+ |
assertThrows( |
1854 |
+ |
UnsupportedOperationException.class, |
1855 |
+ |
new Runnable() { public void run() { |
1856 |
+ |
((Collection) o).add(null);}}); |
1857 |
+ |
} |
1858 |
+ |
} |
1859 |
+ |
|
1860 |
|
@SuppressWarnings("unchecked") |
1861 |
|
<T> T serialClone(T o) { |
1862 |
|
try { |
1863 |
|
ObjectInputStream ois = new ObjectInputStream |
1864 |
|
(new ByteArrayInputStream(serialBytes(o))); |
1865 |
|
T clone = (T) ois.readObject(); |
1866 |
+ |
if (o == clone) assertImmutable(o); |
1867 |
|
assertSame(o.getClass(), clone.getClass()); |
1868 |
|
return clone; |
1869 |
|
} catch (Throwable fail) { |
1872 |
|
} |
1873 |
|
} |
1874 |
|
|
1875 |
+ |
/** |
1876 |
+ |
* A version of serialClone that leaves error handling (for |
1877 |
+ |
* e.g. NotSerializableException) up to the caller. |
1878 |
+ |
*/ |
1879 |
+ |
@SuppressWarnings("unchecked") |
1880 |
+ |
<T> T serialClonePossiblyFailing(T o) |
1881 |
+ |
throws ReflectiveOperationException, java.io.IOException { |
1882 |
+ |
ByteArrayOutputStream bos = new ByteArrayOutputStream(); |
1883 |
+ |
ObjectOutputStream oos = new ObjectOutputStream(bos); |
1884 |
+ |
oos.writeObject(o); |
1885 |
+ |
oos.flush(); |
1886 |
+ |
oos.close(); |
1887 |
+ |
ObjectInputStream ois = new ObjectInputStream |
1888 |
+ |
(new ByteArrayInputStream(bos.toByteArray())); |
1889 |
+ |
T clone = (T) ois.readObject(); |
1890 |
+ |
if (o == clone) assertImmutable(o); |
1891 |
+ |
assertSame(o.getClass(), clone.getClass()); |
1892 |
+ |
return clone; |
1893 |
+ |
} |
1894 |
+ |
|
1895 |
+ |
/** |
1896 |
+ |
* If o implements Cloneable and has a public clone method, |
1897 |
+ |
* returns a clone of o, else null. |
1898 |
+ |
*/ |
1899 |
+ |
@SuppressWarnings("unchecked") |
1900 |
+ |
<T> T cloneableClone(T o) { |
1901 |
+ |
if (!(o instanceof Cloneable)) return null; |
1902 |
+ |
final T clone; |
1903 |
+ |
try { |
1904 |
+ |
clone = (T) o.getClass().getMethod("clone").invoke(o); |
1905 |
+ |
} catch (NoSuchMethodException ok) { |
1906 |
+ |
return null; |
1907 |
+ |
} catch (ReflectiveOperationException unexpected) { |
1908 |
+ |
throw new Error(unexpected); |
1909 |
+ |
} |
1910 |
+ |
assertNotSame(o, clone); // not 100% guaranteed by spec |
1911 |
+ |
assertSame(o.getClass(), clone.getClass()); |
1912 |
+ |
return clone; |
1913 |
+ |
} |
1914 |
+ |
|
1915 |
|
public void assertThrows(Class<? extends Throwable> expectedExceptionClass, |
1916 |
|
Runnable... throwingActions) { |
1917 |
|
for (Runnable throwingAction : throwingActions) { |
1940 |
|
} catch (NoSuchElementException success) {} |
1941 |
|
assertFalse(it.hasNext()); |
1942 |
|
} |
1943 |
+ |
|
1944 |
+ |
public <T> Callable<T> callableThrowing(final Exception ex) { |
1945 |
+ |
return new Callable<T>() { public T call() throws Exception { throw ex; }}; |
1946 |
+ |
} |
1947 |
+ |
|
1948 |
+ |
public Runnable runnableThrowing(final RuntimeException ex) { |
1949 |
+ |
return new Runnable() { public void run() { throw ex; }}; |
1950 |
+ |
} |
1951 |
+ |
|
1952 |
+ |
/** A reusable thread pool to be shared by tests. */ |
1953 |
+ |
static final ExecutorService cachedThreadPool = |
1954 |
+ |
new ThreadPoolExecutor(0, Integer.MAX_VALUE, |
1955 |
+ |
1000L, MILLISECONDS, |
1956 |
+ |
new SynchronousQueue<Runnable>()); |
1957 |
+ |
|
1958 |
+ |
static <T> void shuffle(T[] array) { |
1959 |
+ |
Collections.shuffle(Arrays.asList(array), ThreadLocalRandom.current()); |
1960 |
+ |
} |
1961 |
|
} |