6 |
|
* Pat Fisher, Mike Judd. |
7 |
|
*/ |
8 |
|
|
9 |
< |
import junit.framework.*; |
9 |
> |
import static java.util.concurrent.TimeUnit.MILLISECONDS; |
10 |
> |
import static java.util.concurrent.TimeUnit.NANOSECONDS; |
11 |
> |
|
12 |
|
import java.io.ByteArrayInputStream; |
13 |
|
import java.io.ByteArrayOutputStream; |
14 |
|
import java.io.ObjectInputStream; |
15 |
|
import java.io.ObjectOutputStream; |
16 |
|
import java.lang.management.ManagementFactory; |
17 |
|
import java.lang.management.ThreadInfo; |
18 |
+ |
import java.lang.management.ThreadMXBean; |
19 |
+ |
import java.lang.reflect.Constructor; |
20 |
|
import java.lang.reflect.Method; |
21 |
+ |
import java.lang.reflect.Modifier; |
22 |
+ |
import java.security.CodeSource; |
23 |
+ |
import java.security.Permission; |
24 |
+ |
import java.security.PermissionCollection; |
25 |
+ |
import java.security.Permissions; |
26 |
+ |
import java.security.Policy; |
27 |
+ |
import java.security.ProtectionDomain; |
28 |
+ |
import java.security.SecurityPermission; |
29 |
|
import java.util.ArrayList; |
30 |
|
import java.util.Arrays; |
31 |
|
import java.util.Date; |
32 |
|
import java.util.Enumeration; |
33 |
+ |
import java.util.Iterator; |
34 |
|
import java.util.List; |
35 |
|
import java.util.NoSuchElementException; |
36 |
|
import java.util.PropertyPermission; |
37 |
< |
import java.util.concurrent.*; |
38 |
< |
import java.util.concurrent.atomic.AtomicBoolean; |
37 |
> |
import java.util.concurrent.BlockingQueue; |
38 |
> |
import java.util.concurrent.Callable; |
39 |
> |
import java.util.concurrent.CountDownLatch; |
40 |
> |
import java.util.concurrent.CyclicBarrier; |
41 |
> |
import java.util.concurrent.ExecutionException; |
42 |
> |
import java.util.concurrent.Executors; |
43 |
> |
import java.util.concurrent.ExecutorService; |
44 |
> |
import java.util.concurrent.ForkJoinPool; |
45 |
> |
import java.util.concurrent.Future; |
46 |
> |
import java.util.concurrent.RecursiveAction; |
47 |
> |
import java.util.concurrent.RecursiveTask; |
48 |
> |
import java.util.concurrent.RejectedExecutionHandler; |
49 |
> |
import java.util.concurrent.Semaphore; |
50 |
> |
import java.util.concurrent.ThreadFactory; |
51 |
> |
import java.util.concurrent.ThreadPoolExecutor; |
52 |
> |
import java.util.concurrent.TimeoutException; |
53 |
|
import java.util.concurrent.atomic.AtomicReference; |
54 |
< |
import static java.util.concurrent.TimeUnit.MILLISECONDS; |
55 |
< |
import static java.util.concurrent.TimeUnit.NANOSECONDS; |
56 |
< |
import java.security.CodeSource; |
57 |
< |
import java.security.Permission; |
58 |
< |
import java.security.PermissionCollection; |
59 |
< |
import java.security.Permissions; |
60 |
< |
import java.security.Policy; |
34 |
< |
import java.security.ProtectionDomain; |
35 |
< |
import java.security.SecurityPermission; |
54 |
> |
import java.util.regex.Pattern; |
55 |
> |
|
56 |
> |
import junit.framework.AssertionFailedError; |
57 |
> |
import junit.framework.Test; |
58 |
> |
import junit.framework.TestCase; |
59 |
> |
import junit.framework.TestResult; |
60 |
> |
import junit.framework.TestSuite; |
61 |
|
|
62 |
|
/** |
63 |
|
* Base class for JSR166 Junit TCK tests. Defines some constants, |
69 |
|
* |
70 |
|
* <ol> |
71 |
|
* |
72 |
< |
* <li> All assertions in code running in generated threads must use |
72 |
> |
* <li>All assertions in code running in generated threads must use |
73 |
|
* the forms {@link #threadFail}, {@link #threadAssertTrue}, {@link |
74 |
|
* #threadAssertEquals}, or {@link #threadAssertNull}, (not |
75 |
|
* {@code fail}, {@code assertTrue}, etc.) It is OK (but not |
76 |
|
* particularly recommended) for other code to use these forms too. |
77 |
|
* Only the most typically used JUnit assertion methods are defined |
78 |
< |
* this way, but enough to live with.</li> |
78 |
> |
* this way, but enough to live with. |
79 |
|
* |
80 |
< |
* <li> If you override {@link #setUp} or {@link #tearDown}, make sure |
80 |
> |
* <li>If you override {@link #setUp} or {@link #tearDown}, make sure |
81 |
|
* to invoke {@code super.setUp} and {@code super.tearDown} within |
82 |
|
* them. These methods are used to clear and check for thread |
83 |
< |
* assertion failures.</li> |
83 |
> |
* assertion failures. |
84 |
|
* |
85 |
|
* <li>All delays and timeouts must use one of the constants {@code |
86 |
|
* SHORT_DELAY_MS}, {@code SMALL_DELAY_MS}, {@code MEDIUM_DELAY_MS}, |
91 |
|
* is always discriminable as larger than SHORT and smaller than |
92 |
|
* MEDIUM. And so on. These constants are set to conservative values, |
93 |
|
* but even so, if there is ever any doubt, they can all be increased |
94 |
< |
* in one spot to rerun tests on slower platforms.</li> |
94 |
> |
* in one spot to rerun tests on slower platforms. |
95 |
|
* |
96 |
< |
* <li> All threads generated must be joined inside each test case |
96 |
> |
* <li>All threads generated must be joined inside each test case |
97 |
|
* method (or {@code fail} to do so) before returning from the |
98 |
|
* method. The {@code joinPool} method can be used to do this when |
99 |
< |
* using Executors.</li> |
99 |
> |
* using Executors. |
100 |
|
* |
101 |
|
* </ol> |
102 |
|
* |
103 |
|
* <p><b>Other notes</b> |
104 |
|
* <ul> |
105 |
|
* |
106 |
< |
* <li> Usually, there is one testcase method per JSR166 method |
106 |
> |
* <li>Usually, there is one testcase method per JSR166 method |
107 |
|
* covering "normal" operation, and then as many exception-testing |
108 |
|
* methods as there are exceptions the method can throw. Sometimes |
109 |
|
* there are multiple tests per JSR166 method when the different |
110 |
|
* "normal" behaviors differ significantly. And sometimes testcases |
111 |
|
* cover multiple methods when they cannot be tested in |
112 |
< |
* isolation.</li> |
112 |
> |
* isolation. |
113 |
|
* |
114 |
< |
* <li> The documentation style for testcases is to provide as javadoc |
114 |
> |
* <li>The documentation style for testcases is to provide as javadoc |
115 |
|
* a simple sentence or two describing the property that the testcase |
116 |
|
* method purports to test. The javadocs do not say anything about how |
117 |
< |
* the property is tested. To find out, read the code.</li> |
117 |
> |
* the property is tested. To find out, read the code. |
118 |
|
* |
119 |
< |
* <li> These tests are "conformance tests", and do not attempt to |
119 |
> |
* <li>These tests are "conformance tests", and do not attempt to |
120 |
|
* test throughput, latency, scalability or other performance factors |
121 |
|
* (see the separate "jtreg" tests for a set intended to check these |
122 |
|
* for the most central aspects of functionality.) So, most tests use |
123 |
|
* the smallest sensible numbers of threads, collection sizes, etc |
124 |
< |
* needed to check basic conformance.</li> |
124 |
> |
* needed to check basic conformance. |
125 |
|
* |
126 |
|
* <li>The test classes currently do not declare inclusion in |
127 |
|
* any particular package to simplify things for people integrating |
128 |
< |
* them in TCK test suites.</li> |
128 |
> |
* them in TCK test suites. |
129 |
|
* |
130 |
< |
* <li> As a convenience, the {@code main} of this class (JSR166TestCase) |
131 |
< |
* runs all JSR166 unit tests.</li> |
130 |
> |
* <li>As a convenience, the {@code main} of this class (JSR166TestCase) |
131 |
> |
* runs all JSR166 unit tests. |
132 |
|
* |
133 |
|
* </ul> |
134 |
|
*/ |
140 |
|
Boolean.getBoolean("jsr166.expensiveTests"); |
141 |
|
|
142 |
|
/** |
143 |
+ |
* If true, also run tests that are not part of the official tck |
144 |
+ |
* because they test unspecified implementation details. |
145 |
+ |
*/ |
146 |
+ |
protected static final boolean testImplementationDetails = |
147 |
+ |
Boolean.getBoolean("jsr166.testImplementationDetails"); |
148 |
+ |
|
149 |
+ |
/** |
150 |
|
* If true, report on stdout all "slow" tests, that is, ones that |
151 |
|
* take more than profileThreshold milliseconds to execute. |
152 |
|
*/ |
166 |
|
private static final int runsPerTest = |
167 |
|
Integer.getInteger("jsr166.runsPerTest", 1); |
168 |
|
|
169 |
+ |
/** |
170 |
+ |
* The number of repetitions of the test suite (for finding leaks?). |
171 |
+ |
*/ |
172 |
+ |
private static final int suiteRuns = |
173 |
+ |
Integer.getInteger("jsr166.suiteRuns", 1); |
174 |
+ |
|
175 |
+ |
public JSR166TestCase() { super(); } |
176 |
+ |
public JSR166TestCase(String name) { super(name); } |
177 |
+ |
|
178 |
+ |
/** |
179 |
+ |
* A filter for tests to run, matching strings of the form |
180 |
+ |
* methodName(className), e.g. "testInvokeAll5(ForkJoinPoolTest)" |
181 |
+ |
* Usefully combined with jsr166.runsPerTest. |
182 |
+ |
*/ |
183 |
+ |
private static final Pattern methodFilter = methodFilter(); |
184 |
+ |
|
185 |
+ |
private static Pattern methodFilter() { |
186 |
+ |
String regex = System.getProperty("jsr166.methodFilter"); |
187 |
+ |
return (regex == null) ? null : Pattern.compile(regex); |
188 |
+ |
} |
189 |
+ |
|
190 |
+ |
public void runBare() throws Throwable { |
191 |
+ |
if (methodFilter == null |
192 |
+ |
|| methodFilter.matcher(toString()).find()) |
193 |
+ |
super.runBare(); |
194 |
+ |
} |
195 |
+ |
|
196 |
|
protected void runTest() throws Throwable { |
197 |
|
for (int i = 0; i < runsPerTest; i++) { |
198 |
|
if (profileTests) |
203 |
|
} |
204 |
|
|
205 |
|
protected void runTestProfiled() throws Throwable { |
206 |
< |
long t0 = System.nanoTime(); |
207 |
< |
try { |
206 |
> |
for (int i = 0; i < 2; i++) { |
207 |
> |
long startTime = System.nanoTime(); |
208 |
|
super.runTest(); |
209 |
< |
} finally { |
210 |
< |
long elapsedMillis = |
211 |
< |
(System.nanoTime() - t0) / (1000L * 1000L); |
212 |
< |
if (elapsedMillis >= profileThreshold) |
209 |
> |
long elapsedMillis = millisElapsedSince(startTime); |
210 |
> |
if (elapsedMillis < profileThreshold) |
211 |
> |
break; |
212 |
> |
// Never report first run of any test; treat it as a |
213 |
> |
// warmup run, notably to trigger all needed classloading, |
214 |
> |
if (i > 0) |
215 |
|
System.out.printf("%n%s: %d%n", toString(), elapsedMillis); |
216 |
|
} |
217 |
|
} |
218 |
|
|
219 |
|
/** |
220 |
|
* Runs all JSR166 unit tests using junit.textui.TestRunner. |
160 |
– |
* Optional command line arg provides the number of iterations to |
161 |
– |
* repeat running the tests. |
221 |
|
*/ |
222 |
|
public static void main(String[] args) { |
223 |
+ |
main(suite(), args); |
224 |
+ |
} |
225 |
+ |
|
226 |
+ |
/** |
227 |
+ |
* Runs all unit tests in the given test suite. |
228 |
+ |
* Actual behavior influenced by jsr166.* system properties. |
229 |
+ |
*/ |
230 |
+ |
static void main(Test suite, String[] args) { |
231 |
|
if (useSecurityManager) { |
232 |
|
System.err.println("Setting a permissive security manager"); |
233 |
|
Policy.setPolicy(permissivePolicy()); |
234 |
|
System.setSecurityManager(new SecurityManager()); |
235 |
|
} |
236 |
< |
int iters = (args.length == 0) ? 1 : Integer.parseInt(args[0]); |
237 |
< |
|
238 |
< |
Test s = suite(); |
239 |
< |
for (int i = 0; i < iters; ++i) { |
173 |
< |
junit.textui.TestRunner.run(s); |
236 |
> |
for (int i = 0; i < suiteRuns; i++) { |
237 |
> |
TestResult result = junit.textui.TestRunner.run(suite); |
238 |
> |
if (!result.wasSuccessful()) |
239 |
> |
System.exit(1); |
240 |
|
System.gc(); |
241 |
|
System.runFinalization(); |
242 |
|
} |
177 |
– |
System.exit(0); |
243 |
|
} |
244 |
|
|
245 |
|
public static TestSuite newTestSuite(Object... suiteOrClasses) { |
270 |
|
} |
271 |
|
|
272 |
|
public static final double JAVA_CLASS_VERSION; |
273 |
+ |
public static final String JAVA_SPECIFICATION_VERSION; |
274 |
|
static { |
275 |
|
try { |
276 |
|
JAVA_CLASS_VERSION = java.security.AccessController.doPrivileged( |
277 |
|
new java.security.PrivilegedAction<Double>() { |
278 |
|
public Double run() { |
279 |
|
return Double.valueOf(System.getProperty("java.class.version"));}}); |
280 |
+ |
JAVA_SPECIFICATION_VERSION = java.security.AccessController.doPrivileged( |
281 |
+ |
new java.security.PrivilegedAction<String>() { |
282 |
+ |
public String run() { |
283 |
+ |
return System.getProperty("java.specification.version");}}); |
284 |
|
} catch (Throwable t) { |
285 |
|
throw new Error(t); |
286 |
|
} |
289 |
|
public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; } |
290 |
|
public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; } |
291 |
|
public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; } |
292 |
+ |
public static boolean atLeastJava9() { |
293 |
+ |
return JAVA_CLASS_VERSION >= 53.0 |
294 |
+ |
// As of 2015-09, java9 still uses 52.0 class file version |
295 |
+ |
|| JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?(9|[0-9][0-9])$"); |
296 |
+ |
} |
297 |
+ |
public static boolean atLeastJava10() { |
298 |
+ |
return JAVA_CLASS_VERSION >= 54.0 |
299 |
+ |
|| JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?[0-9][0-9]$"); |
300 |
+ |
} |
301 |
|
|
302 |
|
/** |
303 |
|
* Collects all JSR166 unit tests as one suite. |
373 |
|
// Java8+ test classes |
374 |
|
if (atLeastJava8()) { |
375 |
|
String[] java8TestClassNames = { |
376 |
+ |
"Atomic8Test", |
377 |
|
"CompletableFutureTest", |
378 |
|
"ConcurrentHashMap8Test", |
379 |
|
"CountedCompleterTest", |
385 |
|
"LongAdderTest", |
386 |
|
"SplittableRandomTest", |
387 |
|
"StampedLockTest", |
388 |
+ |
"SubmissionPublisherTest", |
389 |
|
"ThreadLocalRandom8Test", |
390 |
|
}; |
391 |
|
addNamedTestClasses(suite, java8TestClassNames); |
392 |
|
} |
393 |
|
|
394 |
+ |
// Java9+ test classes |
395 |
+ |
if (atLeastJava9()) { |
396 |
+ |
String[] java9TestClassNames = { |
397 |
+ |
// Currently empty, but expecting varhandle tests |
398 |
+ |
}; |
399 |
+ |
addNamedTestClasses(suite, java9TestClassNames); |
400 |
+ |
} |
401 |
+ |
|
402 |
|
return suite; |
403 |
|
} |
404 |
|
|
405 |
+ |
/** Returns list of junit-style test method names in given class. */ |
406 |
+ |
public static ArrayList<String> testMethodNames(Class<?> testClass) { |
407 |
+ |
Method[] methods = testClass.getDeclaredMethods(); |
408 |
+ |
ArrayList<String> names = new ArrayList<String>(methods.length); |
409 |
+ |
for (Method method : methods) { |
410 |
+ |
if (method.getName().startsWith("test") |
411 |
+ |
&& Modifier.isPublic(method.getModifiers()) |
412 |
+ |
// method.getParameterCount() requires jdk8+ |
413 |
+ |
&& method.getParameterTypes().length == 0) { |
414 |
+ |
names.add(method.getName()); |
415 |
+ |
} |
416 |
+ |
} |
417 |
+ |
return names; |
418 |
+ |
} |
419 |
+ |
|
420 |
+ |
/** |
421 |
+ |
* Returns junit-style testSuite for the given test class, but |
422 |
+ |
* parameterized by passing extra data to each test. |
423 |
+ |
*/ |
424 |
+ |
public static <ExtraData> Test parameterizedTestSuite |
425 |
+ |
(Class<? extends JSR166TestCase> testClass, |
426 |
+ |
Class<ExtraData> dataClass, |
427 |
+ |
ExtraData data) { |
428 |
+ |
try { |
429 |
+ |
TestSuite suite = new TestSuite(); |
430 |
+ |
Constructor c = |
431 |
+ |
testClass.getDeclaredConstructor(dataClass, String.class); |
432 |
+ |
for (String methodName : testMethodNames(testClass)) |
433 |
+ |
suite.addTest((Test) c.newInstance(data, methodName)); |
434 |
+ |
return suite; |
435 |
+ |
} catch (Exception e) { |
436 |
+ |
throw new Error(e); |
437 |
+ |
} |
438 |
+ |
} |
439 |
+ |
|
440 |
+ |
/** |
441 |
+ |
* Returns junit-style testSuite for the jdk8 extension of the |
442 |
+ |
* given test class, but parameterized by passing extra data to |
443 |
+ |
* each test. Uses reflection to allow compilation in jdk7. |
444 |
+ |
*/ |
445 |
+ |
public static <ExtraData> Test jdk8ParameterizedTestSuite |
446 |
+ |
(Class<? extends JSR166TestCase> testClass, |
447 |
+ |
Class<ExtraData> dataClass, |
448 |
+ |
ExtraData data) { |
449 |
+ |
if (atLeastJava8()) { |
450 |
+ |
String name = testClass.getName(); |
451 |
+ |
String name8 = name.replaceAll("Test$", "8Test"); |
452 |
+ |
if (name.equals(name8)) throw new Error(name); |
453 |
+ |
try { |
454 |
+ |
return (Test) |
455 |
+ |
Class.forName(name8) |
456 |
+ |
.getMethod("testSuite", new Class[] { dataClass }) |
457 |
+ |
.invoke(null, data); |
458 |
+ |
} catch (Exception e) { |
459 |
+ |
throw new Error(e); |
460 |
+ |
} |
461 |
+ |
} else { |
462 |
+ |
return new TestSuite(); |
463 |
+ |
} |
464 |
+ |
} |
465 |
+ |
|
466 |
|
// Delays for timing-dependent tests, in milliseconds. |
467 |
|
|
468 |
|
public static long SHORT_DELAY_MS; |
497 |
|
} |
498 |
|
|
499 |
|
/** |
500 |
< |
* Returns a new Date instance representing a time delayMillis |
501 |
< |
* milliseconds in the future. |
500 |
> |
* Returns a new Date instance representing a time at least |
501 |
> |
* delayMillis milliseconds in the future. |
502 |
|
*/ |
503 |
|
Date delayedDate(long delayMillis) { |
504 |
< |
return new Date(System.currentTimeMillis() + delayMillis); |
504 |
> |
// Add 1 because currentTimeMillis is known to round into the past. |
505 |
> |
return new Date(System.currentTimeMillis() + delayMillis + 1); |
506 |
|
} |
507 |
|
|
508 |
|
/** |
518 |
|
* the same test have no effect. |
519 |
|
*/ |
520 |
|
public void threadRecordFailure(Throwable t) { |
521 |
+ |
threadDump(); |
522 |
|
threadFailure.compareAndSet(null, t); |
523 |
|
} |
524 |
|
|
526 |
|
setDelays(); |
527 |
|
} |
528 |
|
|
529 |
+ |
void tearDownFail(String format, Object... args) { |
530 |
+ |
String msg = toString() + ": " + String.format(format, args); |
531 |
+ |
System.err.println(msg); |
532 |
+ |
threadDump(); |
533 |
+ |
throw new AssertionFailedError(msg); |
534 |
+ |
} |
535 |
+ |
|
536 |
|
/** |
537 |
|
* Extra checks that get done for all test cases. |
538 |
|
* |
560 |
|
} |
561 |
|
|
562 |
|
if (Thread.interrupted()) |
563 |
< |
throw new AssertionFailedError("interrupt status set in main thread"); |
563 |
> |
tearDownFail("interrupt status set in main thread"); |
564 |
|
|
565 |
|
checkForkJoinPoolThreadLeaks(); |
566 |
|
} |
567 |
|
|
568 |
|
/** |
569 |
< |
* Find missing try { ... } finally { joinPool(e); } |
569 |
> |
* Finds missing try { ... } finally { joinPool(e); } |
570 |
|
*/ |
571 |
|
void checkForkJoinPoolThreadLeaks() throws InterruptedException { |
572 |
< |
Thread[] survivors = new Thread[5]; |
572 |
> |
Thread[] survivors = new Thread[7]; |
573 |
|
int count = Thread.enumerate(survivors); |
574 |
|
for (int i = 0; i < count; i++) { |
575 |
|
Thread thread = survivors[i]; |
577 |
|
if (name.startsWith("ForkJoinPool-")) { |
578 |
|
// give thread some time to terminate |
579 |
|
thread.join(LONG_DELAY_MS); |
580 |
< |
if (!thread.isAlive()) continue; |
581 |
< |
thread.stop(); |
582 |
< |
throw new AssertionFailedError |
424 |
< |
(String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n", |
425 |
< |
toString(), name)); |
580 |
> |
if (thread.isAlive()) |
581 |
> |
tearDownFail("Found leaked ForkJoinPool thread thread=%s", |
582 |
> |
thread); |
583 |
|
} |
584 |
|
} |
585 |
+ |
|
586 |
+ |
if (!ForkJoinPool.commonPool() |
587 |
+ |
.awaitQuiescence(LONG_DELAY_MS, MILLISECONDS)) |
588 |
+ |
tearDownFail("ForkJoin common pool thread stuck"); |
589 |
|
} |
590 |
|
|
591 |
|
/** |
598 |
|
fail(reason); |
599 |
|
} catch (AssertionFailedError t) { |
600 |
|
threadRecordFailure(t); |
601 |
< |
fail(reason); |
601 |
> |
throw t; |
602 |
|
} |
603 |
|
} |
604 |
|
|
666 |
|
public void threadAssertEquals(Object x, Object y) { |
667 |
|
try { |
668 |
|
assertEquals(x, y); |
669 |
< |
} catch (AssertionFailedError t) { |
670 |
< |
threadRecordFailure(t); |
671 |
< |
throw t; |
672 |
< |
} catch (Throwable t) { |
673 |
< |
threadUnexpectedException(t); |
669 |
> |
} catch (AssertionFailedError fail) { |
670 |
> |
threadRecordFailure(fail); |
671 |
> |
throw fail; |
672 |
> |
} catch (Throwable fail) { |
673 |
> |
threadUnexpectedException(fail); |
674 |
|
} |
675 |
|
} |
676 |
|
|
682 |
|
public void threadAssertSame(Object x, Object y) { |
683 |
|
try { |
684 |
|
assertSame(x, y); |
685 |
< |
} catch (AssertionFailedError t) { |
686 |
< |
threadRecordFailure(t); |
687 |
< |
throw t; |
685 |
> |
} catch (AssertionFailedError fail) { |
686 |
> |
threadRecordFailure(fail); |
687 |
> |
throw fail; |
688 |
|
} |
689 |
|
} |
690 |
|
|
744 |
|
} |
745 |
|
|
746 |
|
/** |
747 |
+ |
* Allows use of try-with-resources with per-test thread pools. |
748 |
+ |
*/ |
749 |
+ |
static class PoolCloser<T extends ExecutorService> |
750 |
+ |
implements AutoCloseable { |
751 |
+ |
public final T pool; |
752 |
+ |
public PoolCloser(T pool) { this.pool = pool; } |
753 |
+ |
public void close() { joinPool(pool); } |
754 |
+ |
} |
755 |
+ |
|
756 |
+ |
/** |
757 |
|
* Waits out termination of a thread pool or fails doing so. |
758 |
|
*/ |
759 |
< |
void joinPool(ExecutorService exec) { |
759 |
> |
static void joinPool(ExecutorService pool) { |
760 |
|
try { |
761 |
< |
exec.shutdown(); |
762 |
< |
assertTrue("ExecutorService did not terminate in a timely manner", |
763 |
< |
exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS)); |
761 |
> |
pool.shutdown(); |
762 |
> |
if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS)) |
763 |
> |
fail("ExecutorService " + pool + |
764 |
> |
" did not terminate in a timely manner"); |
765 |
|
} catch (SecurityException ok) { |
766 |
|
// Allowed in case test doesn't have privs |
767 |
< |
} catch (InterruptedException ie) { |
767 |
> |
} catch (InterruptedException fail) { |
768 |
|
fail("Unexpected InterruptedException"); |
769 |
|
} |
770 |
|
} |
771 |
|
|
772 |
+ |
/** Like Runnable, but with the freedom to throw anything */ |
773 |
+ |
interface Action { public void run() throws Throwable; } |
774 |
+ |
|
775 |
+ |
/** |
776 |
+ |
* Runs all the given actions in parallel, failing if any fail. |
777 |
+ |
* Useful for running multiple variants of tests that are |
778 |
+ |
* necessarily individually slow because they must block. |
779 |
+ |
*/ |
780 |
+ |
void testInParallel(Action ... actions) { |
781 |
+ |
try (PoolCloser<ExecutorService> poolCloser |
782 |
+ |
= new PoolCloser<>(Executors.newCachedThreadPool())) { |
783 |
+ |
ExecutorService pool = poolCloser.pool; |
784 |
+ |
ArrayList<Future<?>> futures = new ArrayList<>(actions.length); |
785 |
+ |
for (final Action action : actions) |
786 |
+ |
futures.add(pool.submit(new CheckedRunnable() { |
787 |
+ |
public void realRun() throws Throwable { action.run();}})); |
788 |
+ |
for (Future<?> future : futures) |
789 |
+ |
try { |
790 |
+ |
assertNull(future.get(LONG_DELAY_MS, MILLISECONDS)); |
791 |
+ |
} catch (ExecutionException ex) { |
792 |
+ |
threadUnexpectedException(ex.getCause()); |
793 |
+ |
} catch (Exception ex) { |
794 |
+ |
threadUnexpectedException(ex); |
795 |
+ |
} |
796 |
+ |
} |
797 |
+ |
} |
798 |
+ |
|
799 |
|
/** |
800 |
|
* A debugging tool to print all stack traces, as jstack does. |
801 |
+ |
* Uninteresting threads are filtered out. |
802 |
|
*/ |
803 |
< |
static void printAllStackTraces() { |
804 |
< |
for (ThreadInfo info : |
805 |
< |
ManagementFactory.getThreadMXBean() |
806 |
< |
.dumpAllThreads(true, true)) |
803 |
> |
static void threadDump() { |
804 |
> |
ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); |
805 |
> |
System.err.println("------ stacktrace dump start ------"); |
806 |
> |
for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) { |
807 |
> |
String name = info.getThreadName(); |
808 |
> |
if ("Signal Dispatcher".equals(name)) |
809 |
> |
continue; |
810 |
> |
if ("Reference Handler".equals(name) |
811 |
> |
&& info.getLockName().startsWith("java.lang.ref.Reference$Lock")) |
812 |
> |
continue; |
813 |
> |
if ("Finalizer".equals(name) |
814 |
> |
&& info.getLockName().startsWith("java.lang.ref.ReferenceQueue$Lock")) |
815 |
> |
continue; |
816 |
|
System.err.print(info); |
817 |
+ |
} |
818 |
+ |
System.err.println("------ stacktrace dump end ------"); |
819 |
|
} |
820 |
|
|
821 |
|
/** |
834 |
|
// No need to optimize the failing case via Thread.join. |
835 |
|
delay(millis); |
836 |
|
assertTrue(thread.isAlive()); |
837 |
< |
} catch (InterruptedException ie) { |
837 |
> |
} catch (InterruptedException fail) { |
838 |
|
fail("Unexpected InterruptedException"); |
839 |
|
} |
840 |
|
} |
856 |
|
delay(millis); |
857 |
|
for (Thread thread : threads) |
858 |
|
assertTrue(thread.isAlive()); |
859 |
< |
} catch (InterruptedException ie) { |
859 |
> |
} catch (InterruptedException fail) { |
860 |
|
fail("Unexpected InterruptedException"); |
861 |
|
} |
862 |
|
} |
878 |
|
future.get(timeoutMillis, MILLISECONDS); |
879 |
|
shouldThrow(); |
880 |
|
} catch (TimeoutException success) { |
881 |
< |
} catch (Exception e) { |
882 |
< |
threadUnexpectedException(e); |
881 |
> |
} catch (Exception fail) { |
882 |
> |
threadUnexpectedException(fail); |
883 |
|
} finally { future.cancel(true); } |
884 |
|
assertTrue(millisElapsedSince(startTime) >= timeoutMillis); |
885 |
|
} |
1035 |
|
void sleep(long millis) { |
1036 |
|
try { |
1037 |
|
delay(millis); |
1038 |
< |
} catch (InterruptedException ie) { |
1038 |
> |
} catch (InterruptedException fail) { |
1039 |
|
AssertionFailedError afe = |
1040 |
|
new AssertionFailedError("Unexpected InterruptedException"); |
1041 |
< |
afe.initCause(ie); |
1041 |
> |
afe.initCause(fail); |
1042 |
|
throw afe; |
1043 |
|
} |
1044 |
|
} |
1076 |
|
/** |
1077 |
|
* Returns the number of milliseconds since time given by |
1078 |
|
* startNanoTime, which must have been previously returned from a |
1079 |
< |
* call to {@link System.nanoTime()}. |
1079 |
> |
* call to {@link System#nanoTime()}. |
1080 |
|
*/ |
1081 |
< |
long millisElapsedSince(long startNanoTime) { |
1081 |
> |
static long millisElapsedSince(long startNanoTime) { |
1082 |
|
return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime); |
1083 |
|
} |
1084 |
|
|
1085 |
+ |
// void assertTerminatesPromptly(long timeoutMillis, Runnable r) { |
1086 |
+ |
// long startTime = System.nanoTime(); |
1087 |
+ |
// try { |
1088 |
+ |
// r.run(); |
1089 |
+ |
// } catch (Throwable fail) { threadUnexpectedException(fail); } |
1090 |
+ |
// if (millisElapsedSince(startTime) > timeoutMillis/2) |
1091 |
+ |
// throw new AssertionFailedError("did not return promptly"); |
1092 |
+ |
// } |
1093 |
+ |
|
1094 |
+ |
// void assertTerminatesPromptly(Runnable r) { |
1095 |
+ |
// assertTerminatesPromptly(LONG_DELAY_MS/2, r); |
1096 |
+ |
// } |
1097 |
+ |
|
1098 |
+ |
/** |
1099 |
+ |
* Checks that timed f.get() returns the expected value, and does not |
1100 |
+ |
* wait for the timeout to elapse before returning. |
1101 |
+ |
*/ |
1102 |
+ |
<T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) { |
1103 |
+ |
long startTime = System.nanoTime(); |
1104 |
+ |
try { |
1105 |
+ |
assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS)); |
1106 |
+ |
} catch (Throwable fail) { threadUnexpectedException(fail); } |
1107 |
+ |
if (millisElapsedSince(startTime) > timeoutMillis/2) |
1108 |
+ |
throw new AssertionFailedError("timed get did not return promptly"); |
1109 |
+ |
} |
1110 |
+ |
|
1111 |
+ |
<T> void checkTimedGet(Future<T> f, T expectedValue) { |
1112 |
+ |
checkTimedGet(f, expectedValue, LONG_DELAY_MS); |
1113 |
+ |
} |
1114 |
+ |
|
1115 |
|
/** |
1116 |
|
* Returns a new started daemon Thread running the given runnable. |
1117 |
|
*/ |
1130 |
|
void awaitTermination(Thread t, long timeoutMillis) { |
1131 |
|
try { |
1132 |
|
t.join(timeoutMillis); |
1133 |
< |
} catch (InterruptedException ie) { |
1134 |
< |
threadUnexpectedException(ie); |
1133 |
> |
} catch (InterruptedException fail) { |
1134 |
> |
threadUnexpectedException(fail); |
1135 |
|
} finally { |
1136 |
|
if (t.getState() != Thread.State.TERMINATED) { |
1137 |
|
t.interrupt(); |
1157 |
|
public final void run() { |
1158 |
|
try { |
1159 |
|
realRun(); |
1160 |
< |
} catch (Throwable t) { |
1161 |
< |
threadUnexpectedException(t); |
1160 |
> |
} catch (Throwable fail) { |
1161 |
> |
threadUnexpectedException(fail); |
1162 |
|
} |
1163 |
|
} |
1164 |
|
} |
1212 |
|
threadShouldThrow("InterruptedException"); |
1213 |
|
} catch (InterruptedException success) { |
1214 |
|
threadAssertFalse(Thread.interrupted()); |
1215 |
< |
} catch (Throwable t) { |
1216 |
< |
threadUnexpectedException(t); |
1215 |
> |
} catch (Throwable fail) { |
1216 |
> |
threadUnexpectedException(fail); |
1217 |
|
} |
1218 |
|
} |
1219 |
|
} |
1224 |
|
public final T call() { |
1225 |
|
try { |
1226 |
|
return realCall(); |
1227 |
< |
} catch (Throwable t) { |
1228 |
< |
threadUnexpectedException(t); |
1227 |
> |
} catch (Throwable fail) { |
1228 |
> |
threadUnexpectedException(fail); |
1229 |
|
return null; |
1230 |
|
} |
1231 |
|
} |
1242 |
|
return result; |
1243 |
|
} catch (InterruptedException success) { |
1244 |
|
threadAssertFalse(Thread.interrupted()); |
1245 |
< |
} catch (Throwable t) { |
1246 |
< |
threadUnexpectedException(t); |
1245 |
> |
} catch (Throwable fail) { |
1246 |
> |
threadUnexpectedException(fail); |
1247 |
|
} |
1248 |
|
return null; |
1249 |
|
} |
1260 |
|
public static final String TEST_STRING = "a test string"; |
1261 |
|
|
1262 |
|
public static class StringTask implements Callable<String> { |
1263 |
< |
public String call() { return TEST_STRING; } |
1263 |
> |
final String value; |
1264 |
> |
public StringTask() { this(TEST_STRING); } |
1265 |
> |
public StringTask(String value) { this.value = value; } |
1266 |
> |
public String call() { return value; } |
1267 |
|
} |
1268 |
|
|
1269 |
|
public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) { |
1276 |
|
}}; |
1277 |
|
} |
1278 |
|
|
1279 |
+ |
public Runnable countDowner(final CountDownLatch latch) { |
1280 |
+ |
return new CheckedRunnable() { |
1281 |
+ |
public void realRun() throws InterruptedException { |
1282 |
+ |
latch.countDown(); |
1283 |
+ |
}}; |
1284 |
+ |
} |
1285 |
+ |
|
1286 |
|
public Runnable awaiter(final CountDownLatch latch) { |
1287 |
|
return new CheckedRunnable() { |
1288 |
|
public void realRun() throws InterruptedException { |
1293 |
|
public void await(CountDownLatch latch) { |
1294 |
|
try { |
1295 |
|
assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS)); |
1296 |
< |
} catch (Throwable t) { |
1297 |
< |
threadUnexpectedException(t); |
1296 |
> |
} catch (Throwable fail) { |
1297 |
> |
threadUnexpectedException(fail); |
1298 |
|
} |
1299 |
|
} |
1300 |
|
|
1301 |
|
public void await(Semaphore semaphore) { |
1302 |
|
try { |
1303 |
|
assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS)); |
1304 |
< |
} catch (Throwable t) { |
1305 |
< |
threadUnexpectedException(t); |
1304 |
> |
} catch (Throwable fail) { |
1305 |
> |
threadUnexpectedException(fail); |
1306 |
|
} |
1307 |
|
} |
1308 |
|
|
1496 |
|
@Override protected final void compute() { |
1497 |
|
try { |
1498 |
|
realCompute(); |
1499 |
< |
} catch (Throwable t) { |
1500 |
< |
threadUnexpectedException(t); |
1499 |
> |
} catch (Throwable fail) { |
1500 |
> |
threadUnexpectedException(fail); |
1501 |
|
} |
1502 |
|
} |
1503 |
|
} |
1511 |
|
@Override protected final T compute() { |
1512 |
|
try { |
1513 |
|
return realCompute(); |
1514 |
< |
} catch (Throwable t) { |
1515 |
< |
threadUnexpectedException(t); |
1514 |
> |
} catch (Throwable fail) { |
1515 |
> |
threadUnexpectedException(fail); |
1516 |
|
return null; |
1517 |
|
} |
1518 |
|
} |
1536 |
|
public int await() { |
1537 |
|
try { |
1538 |
|
return super.await(2 * LONG_DELAY_MS, MILLISECONDS); |
1539 |
< |
} catch (TimeoutException e) { |
1539 |
> |
} catch (TimeoutException timedOut) { |
1540 |
|
throw new AssertionFailedError("timed out"); |
1541 |
< |
} catch (Exception e) { |
1541 |
> |
} catch (Exception fail) { |
1542 |
|
AssertionFailedError afe = |
1543 |
< |
new AssertionFailedError("Unexpected exception: " + e); |
1544 |
< |
afe.initCause(e); |
1543 |
> |
new AssertionFailedError("Unexpected exception: " + fail); |
1544 |
> |
afe.initCause(fail); |
1545 |
|
throw afe; |
1546 |
|
} |
1547 |
|
} |
1569 |
|
q.remove(); |
1570 |
|
shouldThrow(); |
1571 |
|
} catch (NoSuchElementException success) {} |
1572 |
< |
} catch (InterruptedException ie) { |
1322 |
< |
threadUnexpectedException(ie); |
1323 |
< |
} |
1572 |
> |
} catch (InterruptedException fail) { threadUnexpectedException(fail); } |
1573 |
|
} |
1574 |
|
|
1575 |
|
void assertSerialEquals(Object x, Object y) { |
1588 |
|
oos.flush(); |
1589 |
|
oos.close(); |
1590 |
|
return bos.toByteArray(); |
1591 |
< |
} catch (Throwable t) { |
1592 |
< |
threadUnexpectedException(t); |
1591 |
> |
} catch (Throwable fail) { |
1592 |
> |
threadUnexpectedException(fail); |
1593 |
|
return new byte[0]; |
1594 |
|
} |
1595 |
|
} |
1602 |
|
T clone = (T) ois.readObject(); |
1603 |
|
assertSame(o.getClass(), clone.getClass()); |
1604 |
|
return clone; |
1605 |
< |
} catch (Throwable t) { |
1606 |
< |
threadUnexpectedException(t); |
1605 |
> |
} catch (Throwable fail) { |
1606 |
> |
threadUnexpectedException(fail); |
1607 |
|
return null; |
1608 |
|
} |
1609 |
|
} |
1628 |
|
shouldThrow(expectedExceptionClass.getName()); |
1629 |
|
} |
1630 |
|
} |
1631 |
+ |
|
1632 |
+ |
public void assertIteratorExhausted(Iterator<?> it) { |
1633 |
+ |
try { |
1634 |
+ |
it.next(); |
1635 |
+ |
shouldThrow(); |
1636 |
+ |
} catch (NoSuchElementException success) {} |
1637 |
+ |
assertFalse(it.hasNext()); |
1638 |
+ |
} |
1639 |
|
} |