6 |
|
* Pat Fisher, Mike Judd. |
7 |
|
*/ |
8 |
|
|
9 |
< |
import junit.framework.*; |
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.base/java.lang:open |
23 |
> |
* java.management |
24 |
> |
* @run junit/othervm/timeout=1000 |
25 |
> |
* -Djsr166.testImplementationDetails=true |
26 |
> |
* JSR166TestCase |
27 |
> |
* @run junit/othervm/timeout=1000 |
28 |
> |
* -Djsr166.testImplementationDetails=true |
29 |
> |
* -Djava.util.concurrent.ForkJoinPool.common.parallelism=0 |
30 |
> |
* JSR166TestCase |
31 |
> |
* @run junit/othervm/timeout=1000 |
32 |
> |
* -Djsr166.testImplementationDetails=true |
33 |
> |
* -Djava.util.concurrent.ForkJoinPool.common.parallelism=1 |
34 |
> |
* -Djava.util.secureRandomSeed=true |
35 |
> |
* JSR166TestCase |
36 |
> |
* @run junit/othervm/timeout=1000/policy=tck.policy |
37 |
> |
* -Djsr166.testImplementationDetails=true |
38 |
> |
* JSR166TestCase |
39 |
> |
*/ |
40 |
> |
|
41 |
> |
import static java.util.concurrent.TimeUnit.MILLISECONDS; |
42 |
> |
import static java.util.concurrent.TimeUnit.MINUTES; |
43 |
> |
import static java.util.concurrent.TimeUnit.NANOSECONDS; |
44 |
> |
|
45 |
|
import java.io.ByteArrayInputStream; |
46 |
|
import java.io.ByteArrayOutputStream; |
47 |
|
import java.io.ObjectInputStream; |
48 |
|
import java.io.ObjectOutputStream; |
49 |
|
import java.lang.management.ManagementFactory; |
50 |
|
import java.lang.management.ThreadInfo; |
51 |
+ |
import java.lang.management.ThreadMXBean; |
52 |
+ |
import java.lang.reflect.Constructor; |
53 |
|
import java.lang.reflect.Method; |
54 |
+ |
import java.lang.reflect.Modifier; |
55 |
+ |
import java.security.CodeSource; |
56 |
+ |
import java.security.Permission; |
57 |
+ |
import java.security.PermissionCollection; |
58 |
+ |
import java.security.Permissions; |
59 |
+ |
import java.security.Policy; |
60 |
+ |
import java.security.ProtectionDomain; |
61 |
+ |
import java.security.SecurityPermission; |
62 |
|
import java.util.ArrayList; |
63 |
|
import java.util.Arrays; |
64 |
+ |
import java.util.Collection; |
65 |
+ |
import java.util.Collections; |
66 |
|
import java.util.Date; |
67 |
|
import java.util.Enumeration; |
68 |
+ |
import java.util.Iterator; |
69 |
|
import java.util.List; |
70 |
|
import java.util.NoSuchElementException; |
71 |
|
import java.util.PropertyPermission; |
72 |
< |
import java.util.concurrent.*; |
72 |
> |
import java.util.concurrent.BlockingQueue; |
73 |
> |
import java.util.concurrent.Callable; |
74 |
> |
import java.util.concurrent.CountDownLatch; |
75 |
> |
import java.util.concurrent.CyclicBarrier; |
76 |
> |
import java.util.concurrent.ExecutionException; |
77 |
> |
import java.util.concurrent.Executors; |
78 |
> |
import java.util.concurrent.ExecutorService; |
79 |
> |
import java.util.concurrent.ForkJoinPool; |
80 |
> |
import java.util.concurrent.Future; |
81 |
> |
import java.util.concurrent.RecursiveAction; |
82 |
> |
import java.util.concurrent.RecursiveTask; |
83 |
> |
import java.util.concurrent.RejectedExecutionHandler; |
84 |
> |
import java.util.concurrent.Semaphore; |
85 |
> |
import java.util.concurrent.SynchronousQueue; |
86 |
> |
import java.util.concurrent.ThreadFactory; |
87 |
> |
import java.util.concurrent.ThreadLocalRandom; |
88 |
> |
import java.util.concurrent.ThreadPoolExecutor; |
89 |
> |
import java.util.concurrent.TimeoutException; |
90 |
|
import java.util.concurrent.atomic.AtomicBoolean; |
91 |
|
import java.util.concurrent.atomic.AtomicReference; |
27 |
– |
import static java.util.concurrent.TimeUnit.MILLISECONDS; |
28 |
– |
import static java.util.concurrent.TimeUnit.NANOSECONDS; |
92 |
|
import java.util.regex.Pattern; |
93 |
< |
import java.security.CodeSource; |
94 |
< |
import java.security.Permission; |
95 |
< |
import java.security.PermissionCollection; |
96 |
< |
import java.security.Permissions; |
97 |
< |
import java.security.Policy; |
98 |
< |
import java.security.ProtectionDomain; |
36 |
< |
import java.security.SecurityPermission; |
93 |
> |
|
94 |
> |
import junit.framework.AssertionFailedError; |
95 |
> |
import junit.framework.Test; |
96 |
> |
import junit.framework.TestCase; |
97 |
> |
import junit.framework.TestResult; |
98 |
> |
import junit.framework.TestSuite; |
99 |
|
|
100 |
|
/** |
101 |
|
* Base class for JSR166 Junit TCK tests. Defines some constants, |
107 |
|
* |
108 |
|
* <ol> |
109 |
|
* |
110 |
< |
* <li> All assertions in code running in generated threads must use |
110 |
> |
* <li>All assertions in code running in generated threads must use |
111 |
|
* the forms {@link #threadFail}, {@link #threadAssertTrue}, {@link |
112 |
|
* #threadAssertEquals}, or {@link #threadAssertNull}, (not |
113 |
|
* {@code fail}, {@code assertTrue}, etc.) It is OK (but not |
114 |
|
* particularly recommended) for other code to use these forms too. |
115 |
|
* Only the most typically used JUnit assertion methods are defined |
116 |
< |
* this way, but enough to live with.</li> |
116 |
> |
* this way, but enough to live with. |
117 |
|
* |
118 |
< |
* <li> If you override {@link #setUp} or {@link #tearDown}, make sure |
118 |
> |
* <li>If you override {@link #setUp} or {@link #tearDown}, make sure |
119 |
|
* to invoke {@code super.setUp} and {@code super.tearDown} within |
120 |
|
* them. These methods are used to clear and check for thread |
121 |
< |
* assertion failures.</li> |
121 |
> |
* assertion failures. |
122 |
|
* |
123 |
|
* <li>All delays and timeouts must use one of the constants {@code |
124 |
|
* SHORT_DELAY_MS}, {@code SMALL_DELAY_MS}, {@code MEDIUM_DELAY_MS}, |
129 |
|
* is always discriminable as larger than SHORT and smaller than |
130 |
|
* MEDIUM. And so on. These constants are set to conservative values, |
131 |
|
* but even so, if there is ever any doubt, they can all be increased |
132 |
< |
* in one spot to rerun tests on slower platforms.</li> |
132 |
> |
* in one spot to rerun tests on slower platforms. |
133 |
|
* |
134 |
< |
* <li> All threads generated must be joined inside each test case |
134 |
> |
* <li>All threads generated must be joined inside each test case |
135 |
|
* method (or {@code fail} to do so) before returning from the |
136 |
|
* method. The {@code joinPool} method can be used to do this when |
137 |
< |
* using Executors.</li> |
137 |
> |
* using Executors. |
138 |
|
* |
139 |
|
* </ol> |
140 |
|
* |
141 |
|
* <p><b>Other notes</b> |
142 |
|
* <ul> |
143 |
|
* |
144 |
< |
* <li> Usually, there is one testcase method per JSR166 method |
144 |
> |
* <li>Usually, there is one testcase method per JSR166 method |
145 |
|
* covering "normal" operation, and then as many exception-testing |
146 |
|
* methods as there are exceptions the method can throw. Sometimes |
147 |
|
* there are multiple tests per JSR166 method when the different |
148 |
|
* "normal" behaviors differ significantly. And sometimes testcases |
149 |
< |
* cover multiple methods when they cannot be tested in |
88 |
< |
* isolation.</li> |
149 |
> |
* cover multiple methods when they cannot be tested in isolation. |
150 |
|
* |
151 |
< |
* <li> The documentation style for testcases is to provide as javadoc |
151 |
> |
* <li>The documentation style for testcases is to provide as javadoc |
152 |
|
* a simple sentence or two describing the property that the testcase |
153 |
|
* method purports to test. The javadocs do not say anything about how |
154 |
< |
* the property is tested. To find out, read the code.</li> |
154 |
> |
* the property is tested. To find out, read the code. |
155 |
|
* |
156 |
< |
* <li> These tests are "conformance tests", and do not attempt to |
156 |
> |
* <li>These tests are "conformance tests", and do not attempt to |
157 |
|
* test throughput, latency, scalability or other performance factors |
158 |
|
* (see the separate "jtreg" tests for a set intended to check these |
159 |
|
* for the most central aspects of functionality.) So, most tests use |
160 |
|
* the smallest sensible numbers of threads, collection sizes, etc |
161 |
< |
* needed to check basic conformance.</li> |
161 |
> |
* needed to check basic conformance. |
162 |
|
* |
163 |
|
* <li>The test classes currently do not declare inclusion in |
164 |
|
* any particular package to simplify things for people integrating |
165 |
< |
* them in TCK test suites.</li> |
165 |
> |
* them in TCK test suites. |
166 |
|
* |
167 |
< |
* <li> As a convenience, the {@code main} of this class (JSR166TestCase) |
168 |
< |
* runs all JSR166 unit tests.</li> |
167 |
> |
* <li>As a convenience, the {@code main} of this class (JSR166TestCase) |
168 |
> |
* runs all JSR166 unit tests. |
169 |
|
* |
170 |
|
* </ul> |
171 |
|
*/ |
177 |
|
Boolean.getBoolean("jsr166.expensiveTests"); |
178 |
|
|
179 |
|
/** |
180 |
+ |
* If true, also run tests that are not part of the official tck |
181 |
+ |
* because they test unspecified implementation details. |
182 |
+ |
*/ |
183 |
+ |
protected static final boolean testImplementationDetails = |
184 |
+ |
Boolean.getBoolean("jsr166.testImplementationDetails"); |
185 |
+ |
|
186 |
+ |
/** |
187 |
|
* If true, report on stdout all "slow" tests, that is, ones that |
188 |
|
* take more than profileThreshold milliseconds to execute. |
189 |
|
*/ |
204 |
|
Integer.getInteger("jsr166.runsPerTest", 1); |
205 |
|
|
206 |
|
/** |
207 |
+ |
* The number of repetitions of the test suite (for finding leaks?). |
208 |
+ |
*/ |
209 |
+ |
private static final int suiteRuns = |
210 |
+ |
Integer.getInteger("jsr166.suiteRuns", 1); |
211 |
+ |
|
212 |
+ |
/** |
213 |
+ |
* Returns the value of the system property, or NaN if not defined. |
214 |
+ |
*/ |
215 |
+ |
private static float systemPropertyValue(String name) { |
216 |
+ |
String floatString = System.getProperty(name); |
217 |
+ |
if (floatString == null) |
218 |
+ |
return Float.NaN; |
219 |
+ |
try { |
220 |
+ |
return Float.parseFloat(floatString); |
221 |
+ |
} catch (NumberFormatException ex) { |
222 |
+ |
throw new IllegalArgumentException( |
223 |
+ |
String.format("Bad float value in system property %s=%s", |
224 |
+ |
name, floatString)); |
225 |
+ |
} |
226 |
+ |
} |
227 |
+ |
|
228 |
+ |
/** |
229 |
+ |
* The scaling factor to apply to standard delays used in tests. |
230 |
+ |
* May be initialized from any of: |
231 |
+ |
* - the "jsr166.delay.factor" system property |
232 |
+ |
* - the "test.timeout.factor" system property (as used by jtreg) |
233 |
+ |
* See: http://openjdk.java.net/jtreg/tag-spec.html |
234 |
+ |
* - hard-coded fuzz factor when using a known slowpoke VM |
235 |
+ |
*/ |
236 |
+ |
private static final float delayFactor = delayFactor(); |
237 |
+ |
|
238 |
+ |
private static float delayFactor() { |
239 |
+ |
float x; |
240 |
+ |
if (!Float.isNaN(x = systemPropertyValue("jsr166.delay.factor"))) |
241 |
+ |
return x; |
242 |
+ |
if (!Float.isNaN(x = systemPropertyValue("test.timeout.factor"))) |
243 |
+ |
return x; |
244 |
+ |
String prop = System.getProperty("java.vm.version"); |
245 |
+ |
if (prop != null && prop.matches(".*debug.*")) |
246 |
+ |
return 4.0f; // How much slower is fastdebug than product?! |
247 |
+ |
return 1.0f; |
248 |
+ |
} |
249 |
+ |
|
250 |
+ |
public JSR166TestCase() { super(); } |
251 |
+ |
public JSR166TestCase(String name) { super(name); } |
252 |
+ |
|
253 |
+ |
/** |
254 |
|
* A filter for tests to run, matching strings of the form |
255 |
|
* methodName(className), e.g. "testInvokeAll5(ForkJoinPoolTest)" |
256 |
|
* Usefully combined with jsr166.runsPerTest. |
262 |
|
return (regex == null) ? null : Pattern.compile(regex); |
263 |
|
} |
264 |
|
|
265 |
< |
protected void runTest() throws Throwable { |
265 |
> |
// Instrumentation to debug very rare, but very annoying hung test runs. |
266 |
> |
static volatile TestCase currentTestCase; |
267 |
> |
// static volatile int currentRun = 0; |
268 |
> |
static { |
269 |
> |
Runnable checkForWedgedTest = new Runnable() { public void run() { |
270 |
> |
// Avoid spurious reports with enormous runsPerTest. |
271 |
> |
// A single test case run should never take more than 1 second. |
272 |
> |
// But let's cap it at the high end too ... |
273 |
> |
final int timeoutMinutes = |
274 |
> |
Math.min(15, Math.max(runsPerTest / 60, 1)); |
275 |
> |
for (TestCase lastTestCase = currentTestCase;;) { |
276 |
> |
try { MINUTES.sleep(timeoutMinutes); } |
277 |
> |
catch (InterruptedException unexpected) { break; } |
278 |
> |
if (lastTestCase == currentTestCase) { |
279 |
> |
System.err.printf( |
280 |
> |
"Looks like we're stuck running test: %s%n", |
281 |
> |
lastTestCase); |
282 |
> |
// System.err.printf( |
283 |
> |
// "Looks like we're stuck running test: %s (%d/%d)%n", |
284 |
> |
// lastTestCase, currentRun, runsPerTest); |
285 |
> |
// System.err.println("availableProcessors=" + |
286 |
> |
// Runtime.getRuntime().availableProcessors()); |
287 |
> |
// System.err.printf("cpu model = %s%n", cpuModel()); |
288 |
> |
dumpTestThreads(); |
289 |
> |
// one stack dump is probably enough; more would be spam |
290 |
> |
break; |
291 |
> |
} |
292 |
> |
lastTestCase = currentTestCase; |
293 |
> |
}}}; |
294 |
> |
Thread thread = new Thread(checkForWedgedTest, "checkForWedgedTest"); |
295 |
> |
thread.setDaemon(true); |
296 |
> |
thread.start(); |
297 |
> |
} |
298 |
> |
|
299 |
> |
// public static String cpuModel() { |
300 |
> |
// try { |
301 |
> |
// java.util.regex.Matcher matcher |
302 |
> |
// = Pattern.compile("model name\\s*: (.*)") |
303 |
> |
// .matcher(new String( |
304 |
> |
// java.nio.file.Files.readAllBytes( |
305 |
> |
// java.nio.file.Paths.get("/proc/cpuinfo")), "UTF-8")); |
306 |
> |
// matcher.find(); |
307 |
> |
// return matcher.group(1); |
308 |
> |
// } catch (Exception ex) { return null; } |
309 |
> |
// } |
310 |
> |
|
311 |
> |
public void runBare() throws Throwable { |
312 |
> |
currentTestCase = this; |
313 |
|
if (methodFilter == null |
314 |
< |
|| methodFilter.matcher(toString()).find()) { |
315 |
< |
for (int i = 0; i < runsPerTest; i++) { |
316 |
< |
if (profileTests) |
317 |
< |
runTestProfiled(); |
318 |
< |
else |
319 |
< |
super.runTest(); |
320 |
< |
} |
314 |
> |
|| methodFilter.matcher(toString()).find()) |
315 |
> |
super.runBare(); |
316 |
> |
} |
317 |
> |
|
318 |
> |
protected void runTest() throws Throwable { |
319 |
> |
for (int i = 0; i < runsPerTest; i++) { |
320 |
> |
// currentRun = i; |
321 |
> |
if (profileTests) |
322 |
> |
runTestProfiled(); |
323 |
> |
else |
324 |
> |
super.runTest(); |
325 |
|
} |
326 |
|
} |
327 |
|
|
328 |
|
protected void runTestProfiled() throws Throwable { |
329 |
< |
// Warmup run, notably to trigger all needed classloading. |
330 |
< |
super.runTest(); |
165 |
< |
long t0 = System.nanoTime(); |
166 |
< |
try { |
329 |
> |
for (int i = 0; i < 2; i++) { |
330 |
> |
long startTime = System.nanoTime(); |
331 |
|
super.runTest(); |
332 |
< |
} finally { |
333 |
< |
long elapsedMillis = millisElapsedSince(t0); |
334 |
< |
if (elapsedMillis >= profileThreshold) |
332 |
> |
long elapsedMillis = millisElapsedSince(startTime); |
333 |
> |
if (elapsedMillis < profileThreshold) |
334 |
> |
break; |
335 |
> |
// Never report first run of any test; treat it as a |
336 |
> |
// warmup run, notably to trigger all needed classloading, |
337 |
> |
if (i > 0) |
338 |
|
System.out.printf("%n%s: %d%n", toString(), elapsedMillis); |
339 |
|
} |
340 |
|
} |
341 |
|
|
342 |
|
/** |
343 |
|
* Runs all JSR166 unit tests using junit.textui.TestRunner. |
177 |
– |
* Optional command line arg provides the number of iterations to |
178 |
– |
* repeat running the tests. |
344 |
|
*/ |
345 |
|
public static void main(String[] args) { |
346 |
+ |
main(suite(), args); |
347 |
+ |
} |
348 |
+ |
|
349 |
+ |
static class PithyResultPrinter extends junit.textui.ResultPrinter { |
350 |
+ |
PithyResultPrinter(java.io.PrintStream writer) { super(writer); } |
351 |
+ |
long runTime; |
352 |
+ |
public void startTest(Test test) {} |
353 |
+ |
protected void printHeader(long runTime) { |
354 |
+ |
this.runTime = runTime; // defer printing for later |
355 |
+ |
} |
356 |
+ |
protected void printFooter(TestResult result) { |
357 |
+ |
if (result.wasSuccessful()) { |
358 |
+ |
getWriter().println("OK (" + result.runCount() + " tests)" |
359 |
+ |
+ " Time: " + elapsedTimeAsString(runTime)); |
360 |
+ |
} else { |
361 |
+ |
getWriter().println("Time: " + elapsedTimeAsString(runTime)); |
362 |
+ |
super.printFooter(result); |
363 |
+ |
} |
364 |
+ |
} |
365 |
+ |
} |
366 |
+ |
|
367 |
+ |
/** |
368 |
+ |
* Returns a TestRunner that doesn't bother with unnecessary |
369 |
+ |
* fluff, like printing a "." for each test case. |
370 |
+ |
*/ |
371 |
+ |
static junit.textui.TestRunner newPithyTestRunner() { |
372 |
+ |
junit.textui.TestRunner runner = new junit.textui.TestRunner(); |
373 |
+ |
runner.setPrinter(new PithyResultPrinter(System.out)); |
374 |
+ |
return runner; |
375 |
+ |
} |
376 |
+ |
|
377 |
+ |
/** |
378 |
+ |
* Runs all unit tests in the given test suite. |
379 |
+ |
* Actual behavior influenced by jsr166.* system properties. |
380 |
+ |
*/ |
381 |
+ |
static void main(Test suite, String[] args) { |
382 |
|
if (useSecurityManager) { |
383 |
|
System.err.println("Setting a permissive security manager"); |
384 |
|
Policy.setPolicy(permissivePolicy()); |
385 |
|
System.setSecurityManager(new SecurityManager()); |
386 |
|
} |
387 |
< |
int iters = (args.length == 0) ? 1 : Integer.parseInt(args[0]); |
388 |
< |
|
389 |
< |
Test s = suite(); |
390 |
< |
for (int i = 0; i < iters; ++i) { |
190 |
< |
junit.textui.TestRunner.run(s); |
387 |
> |
for (int i = 0; i < suiteRuns; i++) { |
388 |
> |
TestResult result = newPithyTestRunner().doRun(suite); |
389 |
> |
if (!result.wasSuccessful()) |
390 |
> |
System.exit(1); |
391 |
|
System.gc(); |
392 |
|
System.runFinalization(); |
393 |
|
} |
194 |
– |
System.exit(0); |
394 |
|
} |
395 |
|
|
396 |
|
public static TestSuite newTestSuite(Object... suiteOrClasses) { |
441 |
|
public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; } |
442 |
|
public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; } |
443 |
|
public static boolean atLeastJava9() { |
444 |
< |
// As of 2014-05, java9 still uses 52.0 class file version |
445 |
< |
return JAVA_SPECIFICATION_VERSION.startsWith("1.9"); |
444 |
> |
return JAVA_CLASS_VERSION >= 53.0 |
445 |
> |
// As of 2015-09, java9 still uses 52.0 class file version |
446 |
> |
|| JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?(9|[0-9][0-9])$"); |
447 |
> |
} |
448 |
> |
public static boolean atLeastJava10() { |
449 |
> |
return JAVA_CLASS_VERSION >= 54.0 |
450 |
> |
|| JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?[0-9][0-9]$"); |
451 |
|
} |
452 |
|
|
453 |
|
/** |
469 |
|
AbstractQueuedLongSynchronizerTest.suite(), |
470 |
|
ArrayBlockingQueueTest.suite(), |
471 |
|
ArrayDequeTest.suite(), |
472 |
+ |
ArrayListTest.suite(), |
473 |
|
AtomicBooleanTest.suite(), |
474 |
|
AtomicIntegerArrayTest.suite(), |
475 |
|
AtomicIntegerFieldUpdaterTest.suite(), |
492 |
|
CopyOnWriteArrayListTest.suite(), |
493 |
|
CopyOnWriteArraySetTest.suite(), |
494 |
|
CountDownLatchTest.suite(), |
495 |
+ |
CountedCompleterTest.suite(), |
496 |
|
CyclicBarrierTest.suite(), |
497 |
|
DelayQueueTest.suite(), |
498 |
|
EntryTest.suite(), |
521 |
|
TreeMapTest.suite(), |
522 |
|
TreeSetTest.suite(), |
523 |
|
TreeSubMapTest.suite(), |
524 |
< |
TreeSubSetTest.suite()); |
524 |
> |
TreeSubSetTest.suite(), |
525 |
> |
VectorTest.suite()); |
526 |
|
|
527 |
|
// Java8+ test classes |
528 |
|
if (atLeastJava8()) { |
529 |
|
String[] java8TestClassNames = { |
530 |
+ |
"ArrayDeque8Test", |
531 |
|
"Atomic8Test", |
532 |
|
"CompletableFutureTest", |
533 |
|
"ConcurrentHashMap8Test", |
534 |
< |
"CountedCompleterTest", |
534 |
> |
"CountedCompleter8Test", |
535 |
|
"DoubleAccumulatorTest", |
536 |
|
"DoubleAdderTest", |
537 |
|
"ForkJoinPool8Test", |
538 |
|
"ForkJoinTask8Test", |
539 |
+ |
"LinkedBlockingDeque8Test", |
540 |
+ |
"LinkedBlockingQueue8Test", |
541 |
|
"LongAccumulatorTest", |
542 |
|
"LongAdderTest", |
543 |
|
"SplittableRandomTest", |
544 |
|
"StampedLockTest", |
545 |
+ |
"SubmissionPublisherTest", |
546 |
|
"ThreadLocalRandom8Test", |
547 |
+ |
"TimeUnit8Test", |
548 |
|
}; |
549 |
|
addNamedTestClasses(suite, java8TestClassNames); |
550 |
|
} |
552 |
|
// Java9+ test classes |
553 |
|
if (atLeastJava9()) { |
554 |
|
String[] java9TestClassNames = { |
555 |
< |
"ThreadPoolExecutor9Test", |
555 |
> |
"AtomicBoolean9Test", |
556 |
> |
"AtomicInteger9Test", |
557 |
> |
"AtomicIntegerArray9Test", |
558 |
> |
"AtomicLong9Test", |
559 |
> |
"AtomicLongArray9Test", |
560 |
> |
"AtomicReference9Test", |
561 |
> |
"AtomicReferenceArray9Test", |
562 |
> |
"ExecutorCompletionService9Test", |
563 |
> |
"ForkJoinPool9Test", |
564 |
|
}; |
565 |
|
addNamedTestClasses(suite, java9TestClassNames); |
566 |
|
} |
568 |
|
return suite; |
569 |
|
} |
570 |
|
|
571 |
+ |
/** Returns list of junit-style test method names in given class. */ |
572 |
+ |
public static ArrayList<String> testMethodNames(Class<?> testClass) { |
573 |
+ |
Method[] methods = testClass.getDeclaredMethods(); |
574 |
+ |
ArrayList<String> names = new ArrayList<>(methods.length); |
575 |
+ |
for (Method method : methods) { |
576 |
+ |
if (method.getName().startsWith("test") |
577 |
+ |
&& Modifier.isPublic(method.getModifiers()) |
578 |
+ |
// method.getParameterCount() requires jdk8+ |
579 |
+ |
&& method.getParameterTypes().length == 0) { |
580 |
+ |
names.add(method.getName()); |
581 |
+ |
} |
582 |
+ |
} |
583 |
+ |
return names; |
584 |
+ |
} |
585 |
+ |
|
586 |
+ |
/** |
587 |
+ |
* Returns junit-style testSuite for the given test class, but |
588 |
+ |
* parameterized by passing extra data to each test. |
589 |
+ |
*/ |
590 |
+ |
public static <ExtraData> Test parameterizedTestSuite |
591 |
+ |
(Class<? extends JSR166TestCase> testClass, |
592 |
+ |
Class<ExtraData> dataClass, |
593 |
+ |
ExtraData data) { |
594 |
+ |
try { |
595 |
+ |
TestSuite suite = new TestSuite(); |
596 |
+ |
Constructor c = |
597 |
+ |
testClass.getDeclaredConstructor(dataClass, String.class); |
598 |
+ |
for (String methodName : testMethodNames(testClass)) |
599 |
+ |
suite.addTest((Test) c.newInstance(data, methodName)); |
600 |
+ |
return suite; |
601 |
+ |
} catch (Exception e) { |
602 |
+ |
throw new Error(e); |
603 |
+ |
} |
604 |
+ |
} |
605 |
+ |
|
606 |
+ |
/** |
607 |
+ |
* Returns junit-style testSuite for the jdk8 extension of the |
608 |
+ |
* given test class, but parameterized by passing extra data to |
609 |
+ |
* each test. Uses reflection to allow compilation in jdk7. |
610 |
+ |
*/ |
611 |
+ |
public static <ExtraData> Test jdk8ParameterizedTestSuite |
612 |
+ |
(Class<? extends JSR166TestCase> testClass, |
613 |
+ |
Class<ExtraData> dataClass, |
614 |
+ |
ExtraData data) { |
615 |
+ |
if (atLeastJava8()) { |
616 |
+ |
String name = testClass.getName(); |
617 |
+ |
String name8 = name.replaceAll("Test$", "8Test"); |
618 |
+ |
if (name.equals(name8)) throw new Error(name); |
619 |
+ |
try { |
620 |
+ |
return (Test) |
621 |
+ |
Class.forName(name8) |
622 |
+ |
.getMethod("testSuite", new Class[] { dataClass }) |
623 |
+ |
.invoke(null, data); |
624 |
+ |
} catch (Exception e) { |
625 |
+ |
throw new Error(e); |
626 |
+ |
} |
627 |
+ |
} else { |
628 |
+ |
return new TestSuite(); |
629 |
+ |
} |
630 |
+ |
} |
631 |
+ |
|
632 |
|
// Delays for timing-dependent tests, in milliseconds. |
633 |
|
|
634 |
|
public static long SHORT_DELAY_MS; |
637 |
|
public static long LONG_DELAY_MS; |
638 |
|
|
639 |
|
/** |
640 |
< |
* Returns the shortest timed delay. This could |
641 |
< |
* be reimplemented to use for example a Property. |
640 |
> |
* Returns the shortest timed delay. This can be scaled up for |
641 |
> |
* slow machines using the jsr166.delay.factor system property, |
642 |
> |
* or via jtreg's -timeoutFactor: flag. |
643 |
> |
* http://openjdk.java.net/jtreg/command-help.html |
644 |
|
*/ |
645 |
|
protected long getShortDelay() { |
646 |
< |
return 50; |
646 |
> |
return (long) (50 * delayFactor); |
647 |
|
} |
648 |
|
|
649 |
|
/** |
665 |
|
} |
666 |
|
|
667 |
|
/** |
668 |
< |
* Returns a new Date instance representing a time delayMillis |
669 |
< |
* milliseconds in the future. |
668 |
> |
* Returns a new Date instance representing a time at least |
669 |
> |
* delayMillis milliseconds in the future. |
670 |
|
*/ |
671 |
|
Date delayedDate(long delayMillis) { |
672 |
< |
return new Date(System.currentTimeMillis() + delayMillis); |
672 |
> |
// Add 1 because currentTimeMillis is known to round into the past. |
673 |
> |
return new Date(System.currentTimeMillis() + delayMillis + 1); |
674 |
|
} |
675 |
|
|
676 |
|
/** |
677 |
|
* The first exception encountered if any threadAssertXXX method fails. |
678 |
|
*/ |
679 |
|
private final AtomicReference<Throwable> threadFailure |
680 |
< |
= new AtomicReference<Throwable>(null); |
680 |
> |
= new AtomicReference<>(null); |
681 |
|
|
682 |
|
/** |
683 |
|
* Records an exception so that it can be rethrown later in the test |
686 |
|
* the same test have no effect. |
687 |
|
*/ |
688 |
|
public void threadRecordFailure(Throwable t) { |
689 |
+ |
System.err.println(t); |
690 |
+ |
dumpTestThreads(); |
691 |
|
threadFailure.compareAndSet(null, t); |
692 |
|
} |
693 |
|
|
695 |
|
setDelays(); |
696 |
|
} |
697 |
|
|
698 |
+ |
void tearDownFail(String format, Object... args) { |
699 |
+ |
String msg = toString() + ": " + String.format(format, args); |
700 |
+ |
System.err.println(msg); |
701 |
+ |
dumpTestThreads(); |
702 |
+ |
throw new AssertionFailedError(msg); |
703 |
+ |
} |
704 |
+ |
|
705 |
|
/** |
706 |
|
* Extra checks that get done for all test cases. |
707 |
|
* |
729 |
|
} |
730 |
|
|
731 |
|
if (Thread.interrupted()) |
732 |
< |
throw new AssertionFailedError("interrupt status set in main thread"); |
732 |
> |
tearDownFail("interrupt status set in main thread"); |
733 |
|
|
734 |
|
checkForkJoinPoolThreadLeaks(); |
735 |
|
} |
736 |
|
|
737 |
|
/** |
738 |
< |
* Find missing try { ... } finally { joinPool(e); } |
738 |
> |
* Finds missing PoolCleaners |
739 |
|
*/ |
740 |
|
void checkForkJoinPoolThreadLeaks() throws InterruptedException { |
741 |
< |
Thread[] survivors = new Thread[5]; |
741 |
> |
Thread[] survivors = new Thread[7]; |
742 |
|
int count = Thread.enumerate(survivors); |
743 |
|
for (int i = 0; i < count; i++) { |
744 |
|
Thread thread = survivors[i]; |
746 |
|
if (name.startsWith("ForkJoinPool-")) { |
747 |
|
// give thread some time to terminate |
748 |
|
thread.join(LONG_DELAY_MS); |
749 |
< |
if (!thread.isAlive()) continue; |
750 |
< |
thread.stop(); |
751 |
< |
throw new AssertionFailedError |
459 |
< |
(String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n", |
460 |
< |
toString(), name)); |
749 |
> |
if (thread.isAlive()) |
750 |
> |
tearDownFail("Found leaked ForkJoinPool thread thread=%s", |
751 |
> |
thread); |
752 |
|
} |
753 |
|
} |
754 |
+ |
|
755 |
+ |
if (!ForkJoinPool.commonPool() |
756 |
+ |
.awaitQuiescence(LONG_DELAY_MS, MILLISECONDS)) |
757 |
+ |
tearDownFail("ForkJoin common pool thread stuck"); |
758 |
|
} |
759 |
|
|
760 |
|
/** |
767 |
|
fail(reason); |
768 |
|
} catch (AssertionFailedError t) { |
769 |
|
threadRecordFailure(t); |
770 |
< |
fail(reason); |
770 |
> |
throw t; |
771 |
|
} |
772 |
|
} |
773 |
|
|
835 |
|
public void threadAssertEquals(Object x, Object y) { |
836 |
|
try { |
837 |
|
assertEquals(x, y); |
838 |
< |
} catch (AssertionFailedError t) { |
839 |
< |
threadRecordFailure(t); |
840 |
< |
throw t; |
841 |
< |
} catch (Throwable t) { |
842 |
< |
threadUnexpectedException(t); |
838 |
> |
} catch (AssertionFailedError fail) { |
839 |
> |
threadRecordFailure(fail); |
840 |
> |
throw fail; |
841 |
> |
} catch (Throwable fail) { |
842 |
> |
threadUnexpectedException(fail); |
843 |
|
} |
844 |
|
} |
845 |
|
|
851 |
|
public void threadAssertSame(Object x, Object y) { |
852 |
|
try { |
853 |
|
assertSame(x, y); |
854 |
< |
} catch (AssertionFailedError t) { |
855 |
< |
threadRecordFailure(t); |
856 |
< |
throw t; |
854 |
> |
} catch (AssertionFailedError fail) { |
855 |
> |
threadRecordFailure(fail); |
856 |
> |
throw fail; |
857 |
|
} |
858 |
|
} |
859 |
|
|
894 |
|
/** |
895 |
|
* Delays, via Thread.sleep, for the given millisecond delay, but |
896 |
|
* if the sleep is shorter than specified, may re-sleep or yield |
897 |
< |
* until time elapses. |
897 |
> |
* until time elapses. Ensures that the given time, as measured |
898 |
> |
* by System.nanoTime(), has elapsed. |
899 |
|
*/ |
900 |
|
static void delay(long millis) throws InterruptedException { |
901 |
< |
long startTime = System.nanoTime(); |
902 |
< |
long ns = millis * 1000 * 1000; |
903 |
< |
for (;;) { |
901 |
> |
long nanos = millis * (1000 * 1000); |
902 |
> |
final long wakeupTime = System.nanoTime() + nanos; |
903 |
> |
do { |
904 |
|
if (millis > 0L) |
905 |
|
Thread.sleep(millis); |
906 |
|
else // too short to sleep |
907 |
|
Thread.yield(); |
908 |
< |
long d = ns - (System.nanoTime() - startTime); |
909 |
< |
if (d > 0L) |
910 |
< |
millis = d / (1000 * 1000); |
911 |
< |
else |
912 |
< |
break; |
908 |
> |
nanos = wakeupTime - System.nanoTime(); |
909 |
> |
millis = nanos / (1000 * 1000); |
910 |
> |
} while (nanos >= 0L); |
911 |
> |
} |
912 |
> |
|
913 |
> |
/** |
914 |
> |
* Allows use of try-with-resources with per-test thread pools. |
915 |
> |
*/ |
916 |
> |
class PoolCleaner implements AutoCloseable { |
917 |
> |
private final ExecutorService pool; |
918 |
> |
public PoolCleaner(ExecutorService pool) { this.pool = pool; } |
919 |
> |
public void close() { joinPool(pool); } |
920 |
> |
} |
921 |
> |
|
922 |
> |
/** |
923 |
> |
* An extension of PoolCleaner that has an action to release the pool. |
924 |
> |
*/ |
925 |
> |
class PoolCleanerWithReleaser extends PoolCleaner { |
926 |
> |
private final Runnable releaser; |
927 |
> |
public PoolCleanerWithReleaser(ExecutorService pool, Runnable releaser) { |
928 |
> |
super(pool); |
929 |
> |
this.releaser = releaser; |
930 |
> |
} |
931 |
> |
public void close() { |
932 |
> |
try { |
933 |
> |
releaser.run(); |
934 |
> |
} finally { |
935 |
> |
super.close(); |
936 |
> |
} |
937 |
|
} |
938 |
|
} |
939 |
|
|
940 |
+ |
PoolCleaner cleaner(ExecutorService pool) { |
941 |
+ |
return new PoolCleaner(pool); |
942 |
+ |
} |
943 |
+ |
|
944 |
+ |
PoolCleaner cleaner(ExecutorService pool, Runnable releaser) { |
945 |
+ |
return new PoolCleanerWithReleaser(pool, releaser); |
946 |
+ |
} |
947 |
+ |
|
948 |
+ |
PoolCleaner cleaner(ExecutorService pool, CountDownLatch latch) { |
949 |
+ |
return new PoolCleanerWithReleaser(pool, releaser(latch)); |
950 |
+ |
} |
951 |
+ |
|
952 |
+ |
Runnable releaser(final CountDownLatch latch) { |
953 |
+ |
return new Runnable() { public void run() { |
954 |
+ |
do { latch.countDown(); } |
955 |
+ |
while (latch.getCount() > 0); |
956 |
+ |
}}; |
957 |
+ |
} |
958 |
+ |
|
959 |
+ |
PoolCleaner cleaner(ExecutorService pool, AtomicBoolean flag) { |
960 |
+ |
return new PoolCleanerWithReleaser(pool, releaser(flag)); |
961 |
+ |
} |
962 |
+ |
|
963 |
+ |
Runnable releaser(final AtomicBoolean flag) { |
964 |
+ |
return new Runnable() { public void run() { flag.set(true); }}; |
965 |
+ |
} |
966 |
+ |
|
967 |
|
/** |
968 |
|
* Waits out termination of a thread pool or fails doing so. |
969 |
|
*/ |
970 |
< |
void joinPool(ExecutorService exec) { |
970 |
> |
void joinPool(ExecutorService pool) { |
971 |
|
try { |
972 |
< |
exec.shutdown(); |
973 |
< |
assertTrue("ExecutorService did not terminate in a timely manner", |
974 |
< |
exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS)); |
972 |
> |
pool.shutdown(); |
973 |
> |
if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS)) { |
974 |
> |
try { |
975 |
> |
threadFail("ExecutorService " + pool + |
976 |
> |
" did not terminate in a timely manner"); |
977 |
> |
} finally { |
978 |
> |
// last resort, for the benefit of subsequent tests |
979 |
> |
pool.shutdownNow(); |
980 |
> |
pool.awaitTermination(MEDIUM_DELAY_MS, MILLISECONDS); |
981 |
> |
} |
982 |
> |
} |
983 |
|
} catch (SecurityException ok) { |
984 |
|
// Allowed in case test doesn't have privs |
985 |
< |
} catch (InterruptedException ie) { |
986 |
< |
fail("Unexpected InterruptedException"); |
985 |
> |
} catch (InterruptedException fail) { |
986 |
> |
threadFail("Unexpected InterruptedException"); |
987 |
|
} |
988 |
|
} |
989 |
|
|
990 |
|
/** |
991 |
< |
* A debugging tool to print all stack traces, as jstack does. |
991 |
> |
* Like Runnable, but with the freedom to throw anything. |
992 |
> |
* junit folks had the same idea: |
993 |
> |
* http://junit.org/junit5/docs/snapshot/api/org/junit/gen5/api/Executable.html |
994 |
> |
*/ |
995 |
> |
interface Action { public void run() throws Throwable; } |
996 |
> |
|
997 |
> |
/** |
998 |
> |
* Runs all the given actions in parallel, failing if any fail. |
999 |
> |
* Useful for running multiple variants of tests that are |
1000 |
> |
* necessarily individually slow because they must block. |
1001 |
|
*/ |
1002 |
< |
static void printAllStackTraces() { |
1003 |
< |
for (ThreadInfo info : |
1004 |
< |
ManagementFactory.getThreadMXBean() |
1005 |
< |
.dumpAllThreads(true, true)) |
1002 |
> |
void testInParallel(Action ... actions) { |
1003 |
> |
ExecutorService pool = Executors.newCachedThreadPool(); |
1004 |
> |
try (PoolCleaner cleaner = cleaner(pool)) { |
1005 |
> |
ArrayList<Future<?>> futures = new ArrayList<>(actions.length); |
1006 |
> |
for (final Action action : actions) |
1007 |
> |
futures.add(pool.submit(new CheckedRunnable() { |
1008 |
> |
public void realRun() throws Throwable { action.run();}})); |
1009 |
> |
for (Future<?> future : futures) |
1010 |
> |
try { |
1011 |
> |
assertNull(future.get(LONG_DELAY_MS, MILLISECONDS)); |
1012 |
> |
} catch (ExecutionException ex) { |
1013 |
> |
threadUnexpectedException(ex.getCause()); |
1014 |
> |
} catch (Exception ex) { |
1015 |
> |
threadUnexpectedException(ex); |
1016 |
> |
} |
1017 |
> |
} |
1018 |
> |
} |
1019 |
> |
|
1020 |
> |
/** |
1021 |
> |
* A debugging tool to print stack traces of most threads, as jstack does. |
1022 |
> |
* Uninteresting threads are filtered out. |
1023 |
> |
*/ |
1024 |
> |
static void dumpTestThreads() { |
1025 |
> |
SecurityManager sm = System.getSecurityManager(); |
1026 |
> |
if (sm != null) { |
1027 |
> |
try { |
1028 |
> |
System.setSecurityManager(null); |
1029 |
> |
} catch (SecurityException giveUp) { |
1030 |
> |
return; |
1031 |
> |
} |
1032 |
> |
} |
1033 |
> |
|
1034 |
> |
ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); |
1035 |
> |
System.err.println("------ stacktrace dump start ------"); |
1036 |
> |
for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) { |
1037 |
> |
final String name = info.getThreadName(); |
1038 |
> |
String lockName; |
1039 |
> |
if ("Signal Dispatcher".equals(name)) |
1040 |
> |
continue; |
1041 |
> |
if ("Reference Handler".equals(name) |
1042 |
> |
&& (lockName = info.getLockName()) != null |
1043 |
> |
&& lockName.startsWith("java.lang.ref.Reference$Lock")) |
1044 |
> |
continue; |
1045 |
> |
if ("Finalizer".equals(name) |
1046 |
> |
&& (lockName = info.getLockName()) != null |
1047 |
> |
&& lockName.startsWith("java.lang.ref.ReferenceQueue$Lock")) |
1048 |
> |
continue; |
1049 |
> |
if ("checkForWedgedTest".equals(name)) |
1050 |
> |
continue; |
1051 |
|
System.err.print(info); |
1052 |
+ |
} |
1053 |
+ |
System.err.println("------ stacktrace dump end ------"); |
1054 |
+ |
|
1055 |
+ |
if (sm != null) System.setSecurityManager(sm); |
1056 |
|
} |
1057 |
|
|
1058 |
|
/** |
1071 |
|
// No need to optimize the failing case via Thread.join. |
1072 |
|
delay(millis); |
1073 |
|
assertTrue(thread.isAlive()); |
1074 |
< |
} catch (InterruptedException ie) { |
1075 |
< |
fail("Unexpected InterruptedException"); |
1074 |
> |
} catch (InterruptedException fail) { |
1075 |
> |
threadFail("Unexpected InterruptedException"); |
1076 |
|
} |
1077 |
|
} |
1078 |
|
|
1093 |
|
delay(millis); |
1094 |
|
for (Thread thread : threads) |
1095 |
|
assertTrue(thread.isAlive()); |
1096 |
< |
} catch (InterruptedException ie) { |
1097 |
< |
fail("Unexpected InterruptedException"); |
1096 |
> |
} catch (InterruptedException fail) { |
1097 |
> |
threadFail("Unexpected InterruptedException"); |
1098 |
|
} |
1099 |
|
} |
1100 |
|
|
1115 |
|
future.get(timeoutMillis, MILLISECONDS); |
1116 |
|
shouldThrow(); |
1117 |
|
} catch (TimeoutException success) { |
1118 |
< |
} catch (Exception e) { |
1119 |
< |
threadUnexpectedException(e); |
1118 |
> |
} catch (Exception fail) { |
1119 |
> |
threadUnexpectedException(fail); |
1120 |
|
} finally { future.cancel(true); } |
1121 |
|
assertTrue(millisElapsedSince(startTime) >= timeoutMillis); |
1122 |
|
} |
1239 |
|
} |
1240 |
|
public void refresh() {} |
1241 |
|
public String toString() { |
1242 |
< |
List<Permission> ps = new ArrayList<Permission>(); |
1242 |
> |
List<Permission> ps = new ArrayList<>(); |
1243 |
|
for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();) |
1244 |
|
ps.add(e.nextElement()); |
1245 |
|
return "AdjustablePolicy with permissions " + ps; |
1269 |
|
* Sleeps until the given time has elapsed. |
1270 |
|
* Throws AssertionFailedError if interrupted. |
1271 |
|
*/ |
1272 |
< |
void sleep(long millis) { |
1272 |
> |
static void sleep(long millis) { |
1273 |
|
try { |
1274 |
|
delay(millis); |
1275 |
< |
} catch (InterruptedException ie) { |
1275 |
> |
} catch (InterruptedException fail) { |
1276 |
|
AssertionFailedError afe = |
1277 |
|
new AssertionFailedError("Unexpected InterruptedException"); |
1278 |
< |
afe.initCause(ie); |
1278 |
> |
afe.initCause(fail); |
1279 |
|
throw afe; |
1280 |
|
} |
1281 |
|
} |
1285 |
|
* thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING. |
1286 |
|
*/ |
1287 |
|
void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) { |
1288 |
< |
long startTime = System.nanoTime(); |
1288 |
> |
long startTime = 0L; |
1289 |
|
for (;;) { |
1290 |
|
Thread.State s = thread.getState(); |
1291 |
|
if (s == Thread.State.BLOCKED || |
1294 |
|
return; |
1295 |
|
else if (s == Thread.State.TERMINATED) |
1296 |
|
fail("Unexpected thread termination"); |
1297 |
+ |
else if (startTime == 0L) |
1298 |
+ |
startTime = System.nanoTime(); |
1299 |
|
else if (millisElapsedSince(startTime) > timeoutMillis) { |
1300 |
|
threadAssertTrue(thread.isAlive()); |
1301 |
< |
return; |
1301 |
> |
fail("timed out waiting for thread to enter wait state"); |
1302 |
|
} |
1303 |
|
Thread.yield(); |
1304 |
|
} |
1305 |
|
} |
1306 |
|
|
1307 |
|
/** |
1308 |
< |
* Waits up to LONG_DELAY_MS for the given thread to enter a wait |
1309 |
< |
* state: BLOCKED, WAITING, or TIMED_WAITING. |
1308 |
> |
* Spin-waits up to the specified number of milliseconds for the given |
1309 |
> |
* thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING, |
1310 |
> |
* and additionally satisfy the given condition. |
1311 |
> |
*/ |
1312 |
> |
void waitForThreadToEnterWaitState( |
1313 |
> |
Thread thread, long timeoutMillis, Callable<Boolean> waitingForGodot) { |
1314 |
> |
long startTime = 0L; |
1315 |
> |
for (;;) { |
1316 |
> |
Thread.State s = thread.getState(); |
1317 |
> |
if (s == Thread.State.BLOCKED || |
1318 |
> |
s == Thread.State.WAITING || |
1319 |
> |
s == Thread.State.TIMED_WAITING) { |
1320 |
> |
try { |
1321 |
> |
if (waitingForGodot.call()) |
1322 |
> |
return; |
1323 |
> |
} catch (Throwable fail) { threadUnexpectedException(fail); } |
1324 |
> |
} |
1325 |
> |
else if (s == Thread.State.TERMINATED) |
1326 |
> |
fail("Unexpected thread termination"); |
1327 |
> |
else if (startTime == 0L) |
1328 |
> |
startTime = System.nanoTime(); |
1329 |
> |
else if (millisElapsedSince(startTime) > timeoutMillis) { |
1330 |
> |
threadAssertTrue(thread.isAlive()); |
1331 |
> |
fail("timed out waiting for thread to enter wait state"); |
1332 |
> |
} |
1333 |
> |
Thread.yield(); |
1334 |
> |
} |
1335 |
> |
} |
1336 |
> |
|
1337 |
> |
/** |
1338 |
> |
* Spin-waits up to LONG_DELAY_MS milliseconds for the given thread to |
1339 |
> |
* enter a wait state: BLOCKED, WAITING, or TIMED_WAITING. |
1340 |
|
*/ |
1341 |
|
void waitForThreadToEnterWaitState(Thread thread) { |
1342 |
|
waitForThreadToEnterWaitState(thread, LONG_DELAY_MS); |
1343 |
|
} |
1344 |
|
|
1345 |
|
/** |
1346 |
+ |
* Spin-waits up to LONG_DELAY_MS milliseconds for the given thread to |
1347 |
+ |
* enter a wait state: BLOCKED, WAITING, or TIMED_WAITING, |
1348 |
+ |
* and additionally satisfy the given condition. |
1349 |
+ |
*/ |
1350 |
+ |
void waitForThreadToEnterWaitState( |
1351 |
+ |
Thread thread, Callable<Boolean> waitingForGodot) { |
1352 |
+ |
waitForThreadToEnterWaitState(thread, LONG_DELAY_MS, waitingForGodot); |
1353 |
+ |
} |
1354 |
+ |
|
1355 |
+ |
/** |
1356 |
|
* Returns the number of milliseconds since time given by |
1357 |
|
* startNanoTime, which must have been previously returned from a |
1358 |
< |
* call to {@link System.nanoTime()}. |
1358 |
> |
* call to {@link System#nanoTime()}. |
1359 |
|
*/ |
1360 |
< |
long millisElapsedSince(long startNanoTime) { |
1360 |
> |
static long millisElapsedSince(long startNanoTime) { |
1361 |
|
return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime); |
1362 |
|
} |
1363 |
|
|
1364 |
+ |
// void assertTerminatesPromptly(long timeoutMillis, Runnable r) { |
1365 |
+ |
// long startTime = System.nanoTime(); |
1366 |
+ |
// try { |
1367 |
+ |
// r.run(); |
1368 |
+ |
// } catch (Throwable fail) { threadUnexpectedException(fail); } |
1369 |
+ |
// if (millisElapsedSince(startTime) > timeoutMillis/2) |
1370 |
+ |
// throw new AssertionFailedError("did not return promptly"); |
1371 |
+ |
// } |
1372 |
+ |
|
1373 |
+ |
// void assertTerminatesPromptly(Runnable r) { |
1374 |
+ |
// assertTerminatesPromptly(LONG_DELAY_MS/2, r); |
1375 |
+ |
// } |
1376 |
+ |
|
1377 |
+ |
/** |
1378 |
+ |
* Checks that timed f.get() returns the expected value, and does not |
1379 |
+ |
* wait for the timeout to elapse before returning. |
1380 |
+ |
*/ |
1381 |
+ |
<T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) { |
1382 |
+ |
long startTime = System.nanoTime(); |
1383 |
+ |
try { |
1384 |
+ |
assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS)); |
1385 |
+ |
} catch (Throwable fail) { threadUnexpectedException(fail); } |
1386 |
+ |
if (millisElapsedSince(startTime) > timeoutMillis/2) |
1387 |
+ |
throw new AssertionFailedError("timed get did not return promptly"); |
1388 |
+ |
} |
1389 |
+ |
|
1390 |
+ |
<T> void checkTimedGet(Future<T> f, T expectedValue) { |
1391 |
+ |
checkTimedGet(f, expectedValue, LONG_DELAY_MS); |
1392 |
+ |
} |
1393 |
+ |
|
1394 |
|
/** |
1395 |
|
* Returns a new started daemon Thread running the given runnable. |
1396 |
|
*/ |
1409 |
|
void awaitTermination(Thread t, long timeoutMillis) { |
1410 |
|
try { |
1411 |
|
t.join(timeoutMillis); |
1412 |
< |
} catch (InterruptedException ie) { |
1413 |
< |
threadUnexpectedException(ie); |
1412 |
> |
} catch (InterruptedException fail) { |
1413 |
> |
threadUnexpectedException(fail); |
1414 |
|
} finally { |
1415 |
|
if (t.getState() != Thread.State.TERMINATED) { |
1416 |
|
t.interrupt(); |
1417 |
< |
fail("Test timed out"); |
1417 |
> |
threadFail("timed out waiting for thread to terminate"); |
1418 |
|
} |
1419 |
|
} |
1420 |
|
} |
1436 |
|
public final void run() { |
1437 |
|
try { |
1438 |
|
realRun(); |
1439 |
< |
} catch (Throwable t) { |
1440 |
< |
threadUnexpectedException(t); |
1439 |
> |
} catch (Throwable fail) { |
1440 |
> |
threadUnexpectedException(fail); |
1441 |
|
} |
1442 |
|
} |
1443 |
|
} |
1491 |
|
threadShouldThrow("InterruptedException"); |
1492 |
|
} catch (InterruptedException success) { |
1493 |
|
threadAssertFalse(Thread.interrupted()); |
1494 |
< |
} catch (Throwable t) { |
1495 |
< |
threadUnexpectedException(t); |
1494 |
> |
} catch (Throwable fail) { |
1495 |
> |
threadUnexpectedException(fail); |
1496 |
|
} |
1497 |
|
} |
1498 |
|
} |
1503 |
|
public final T call() { |
1504 |
|
try { |
1505 |
|
return realCall(); |
1506 |
< |
} catch (Throwable t) { |
1507 |
< |
threadUnexpectedException(t); |
1506 |
> |
} catch (Throwable fail) { |
1507 |
> |
threadUnexpectedException(fail); |
1508 |
|
return null; |
1509 |
|
} |
1510 |
|
} |
1521 |
|
return result; |
1522 |
|
} catch (InterruptedException success) { |
1523 |
|
threadAssertFalse(Thread.interrupted()); |
1524 |
< |
} catch (Throwable t) { |
1525 |
< |
threadUnexpectedException(t); |
1524 |
> |
} catch (Throwable fail) { |
1525 |
> |
threadUnexpectedException(fail); |
1526 |
|
} |
1527 |
|
return null; |
1528 |
|
} |
1539 |
|
public static final String TEST_STRING = "a test string"; |
1540 |
|
|
1541 |
|
public static class StringTask implements Callable<String> { |
1542 |
< |
public String call() { return TEST_STRING; } |
1542 |
> |
final String value; |
1543 |
> |
public StringTask() { this(TEST_STRING); } |
1544 |
> |
public StringTask(String value) { this.value = value; } |
1545 |
> |
public String call() { return value; } |
1546 |
|
} |
1547 |
|
|
1548 |
|
public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) { |
1555 |
|
}}; |
1556 |
|
} |
1557 |
|
|
1558 |
< |
public Runnable awaiter(final CountDownLatch latch) { |
1558 |
> |
public Runnable countDowner(final CountDownLatch latch) { |
1559 |
|
return new CheckedRunnable() { |
1560 |
|
public void realRun() throws InterruptedException { |
1561 |
< |
await(latch); |
1561 |
> |
latch.countDown(); |
1562 |
|
}}; |
1563 |
|
} |
1564 |
|
|
1565 |
< |
public void await(CountDownLatch latch) { |
1565 |
> |
class LatchAwaiter extends CheckedRunnable { |
1566 |
> |
static final int NEW = 0; |
1567 |
> |
static final int RUNNING = 1; |
1568 |
> |
static final int DONE = 2; |
1569 |
> |
final CountDownLatch latch; |
1570 |
> |
int state = NEW; |
1571 |
> |
LatchAwaiter(CountDownLatch latch) { this.latch = latch; } |
1572 |
> |
public void realRun() throws InterruptedException { |
1573 |
> |
state = 1; |
1574 |
> |
await(latch); |
1575 |
> |
state = 2; |
1576 |
> |
} |
1577 |
> |
} |
1578 |
> |
|
1579 |
> |
public LatchAwaiter awaiter(CountDownLatch latch) { |
1580 |
> |
return new LatchAwaiter(latch); |
1581 |
> |
} |
1582 |
> |
|
1583 |
> |
public void await(CountDownLatch latch, long timeoutMillis) { |
1584 |
|
try { |
1585 |
< |
assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS)); |
1586 |
< |
} catch (Throwable t) { |
1587 |
< |
threadUnexpectedException(t); |
1585 |
> |
if (!latch.await(timeoutMillis, MILLISECONDS)) |
1586 |
> |
fail("timed out waiting for CountDownLatch for " |
1587 |
> |
+ (timeoutMillis/1000) + " sec"); |
1588 |
> |
} catch (Throwable fail) { |
1589 |
> |
threadUnexpectedException(fail); |
1590 |
|
} |
1591 |
|
} |
1592 |
|
|
1593 |
+ |
public void await(CountDownLatch latch) { |
1594 |
+ |
await(latch, LONG_DELAY_MS); |
1595 |
+ |
} |
1596 |
+ |
|
1597 |
|
public void await(Semaphore semaphore) { |
1598 |
|
try { |
1599 |
< |
assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS)); |
1600 |
< |
} catch (Throwable t) { |
1601 |
< |
threadUnexpectedException(t); |
1599 |
> |
if (!semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS)) |
1600 |
> |
fail("timed out waiting for Semaphore for " |
1601 |
> |
+ (LONG_DELAY_MS/1000) + " sec"); |
1602 |
> |
} catch (Throwable fail) { |
1603 |
> |
threadUnexpectedException(fail); |
1604 |
|
} |
1605 |
|
} |
1606 |
|
|
1794 |
|
@Override protected final void compute() { |
1795 |
|
try { |
1796 |
|
realCompute(); |
1797 |
< |
} catch (Throwable t) { |
1798 |
< |
threadUnexpectedException(t); |
1797 |
> |
} catch (Throwable fail) { |
1798 |
> |
threadUnexpectedException(fail); |
1799 |
|
} |
1800 |
|
} |
1801 |
|
} |
1809 |
|
@Override protected final T compute() { |
1810 |
|
try { |
1811 |
|
return realCompute(); |
1812 |
< |
} catch (Throwable t) { |
1813 |
< |
threadUnexpectedException(t); |
1812 |
> |
} catch (Throwable fail) { |
1813 |
> |
threadUnexpectedException(fail); |
1814 |
|
return null; |
1815 |
|
} |
1816 |
|
} |
1828 |
|
* A CyclicBarrier that uses timed await and fails with |
1829 |
|
* AssertionFailedErrors instead of throwing checked exceptions. |
1830 |
|
*/ |
1831 |
< |
public class CheckedBarrier extends CyclicBarrier { |
1831 |
> |
public static class CheckedBarrier extends CyclicBarrier { |
1832 |
|
public CheckedBarrier(int parties) { super(parties); } |
1833 |
|
|
1834 |
|
public int await() { |
1835 |
|
try { |
1836 |
|
return super.await(2 * LONG_DELAY_MS, MILLISECONDS); |
1837 |
< |
} catch (TimeoutException e) { |
1837 |
> |
} catch (TimeoutException timedOut) { |
1838 |
|
throw new AssertionFailedError("timed out"); |
1839 |
< |
} catch (Exception e) { |
1839 |
> |
} catch (Exception fail) { |
1840 |
|
AssertionFailedError afe = |
1841 |
< |
new AssertionFailedError("Unexpected exception: " + e); |
1842 |
< |
afe.initCause(e); |
1841 |
> |
new AssertionFailedError("Unexpected exception: " + fail); |
1842 |
> |
afe.initCause(fail); |
1843 |
|
throw afe; |
1844 |
|
} |
1845 |
|
} |
1867 |
|
q.remove(); |
1868 |
|
shouldThrow(); |
1869 |
|
} catch (NoSuchElementException success) {} |
1870 |
< |
} catch (InterruptedException ie) { |
1357 |
< |
threadUnexpectedException(ie); |
1358 |
< |
} |
1870 |
> |
} catch (InterruptedException fail) { threadUnexpectedException(fail); } |
1871 |
|
} |
1872 |
|
|
1873 |
|
void assertSerialEquals(Object x, Object y) { |
1886 |
|
oos.flush(); |
1887 |
|
oos.close(); |
1888 |
|
return bos.toByteArray(); |
1889 |
< |
} catch (Throwable t) { |
1890 |
< |
threadUnexpectedException(t); |
1889 |
> |
} catch (Throwable fail) { |
1890 |
> |
threadUnexpectedException(fail); |
1891 |
|
return new byte[0]; |
1892 |
|
} |
1893 |
|
} |
1894 |
|
|
1895 |
+ |
void assertImmutable(final Object o) { |
1896 |
+ |
if (o instanceof Collection) { |
1897 |
+ |
assertThrows( |
1898 |
+ |
UnsupportedOperationException.class, |
1899 |
+ |
new Runnable() { public void run() { |
1900 |
+ |
((Collection) o).add(null);}}); |
1901 |
+ |
} |
1902 |
+ |
} |
1903 |
+ |
|
1904 |
|
@SuppressWarnings("unchecked") |
1905 |
|
<T> T serialClone(T o) { |
1906 |
|
try { |
1907 |
|
ObjectInputStream ois = new ObjectInputStream |
1908 |
|
(new ByteArrayInputStream(serialBytes(o))); |
1909 |
|
T clone = (T) ois.readObject(); |
1910 |
+ |
if (o == clone) assertImmutable(o); |
1911 |
|
assertSame(o.getClass(), clone.getClass()); |
1912 |
|
return clone; |
1913 |
< |
} catch (Throwable t) { |
1914 |
< |
threadUnexpectedException(t); |
1913 |
> |
} catch (Throwable fail) { |
1914 |
> |
threadUnexpectedException(fail); |
1915 |
|
return null; |
1916 |
|
} |
1917 |
|
} |
1918 |
|
|
1919 |
+ |
/** |
1920 |
+ |
* A version of serialClone that leaves error handling (for |
1921 |
+ |
* e.g. NotSerializableException) up to the caller. |
1922 |
+ |
*/ |
1923 |
+ |
@SuppressWarnings("unchecked") |
1924 |
+ |
<T> T serialClonePossiblyFailing(T o) |
1925 |
+ |
throws ReflectiveOperationException, java.io.IOException { |
1926 |
+ |
ByteArrayOutputStream bos = new ByteArrayOutputStream(); |
1927 |
+ |
ObjectOutputStream oos = new ObjectOutputStream(bos); |
1928 |
+ |
oos.writeObject(o); |
1929 |
+ |
oos.flush(); |
1930 |
+ |
oos.close(); |
1931 |
+ |
ObjectInputStream ois = new ObjectInputStream |
1932 |
+ |
(new ByteArrayInputStream(bos.toByteArray())); |
1933 |
+ |
T clone = (T) ois.readObject(); |
1934 |
+ |
if (o == clone) assertImmutable(o); |
1935 |
+ |
assertSame(o.getClass(), clone.getClass()); |
1936 |
+ |
return clone; |
1937 |
+ |
} |
1938 |
+ |
|
1939 |
+ |
/** |
1940 |
+ |
* If o implements Cloneable and has a public clone method, |
1941 |
+ |
* returns a clone of o, else null. |
1942 |
+ |
*/ |
1943 |
+ |
@SuppressWarnings("unchecked") |
1944 |
+ |
<T> T cloneableClone(T o) { |
1945 |
+ |
if (!(o instanceof Cloneable)) return null; |
1946 |
+ |
final T clone; |
1947 |
+ |
try { |
1948 |
+ |
clone = (T) o.getClass().getMethod("clone").invoke(o); |
1949 |
+ |
} catch (NoSuchMethodException ok) { |
1950 |
+ |
return null; |
1951 |
+ |
} catch (ReflectiveOperationException unexpected) { |
1952 |
+ |
throw new Error(unexpected); |
1953 |
+ |
} |
1954 |
+ |
assertNotSame(o, clone); // not 100% guaranteed by spec |
1955 |
+ |
assertSame(o.getClass(), clone.getClass()); |
1956 |
+ |
return clone; |
1957 |
+ |
} |
1958 |
+ |
|
1959 |
|
public void assertThrows(Class<? extends Throwable> expectedExceptionClass, |
1960 |
|
Runnable... throwingActions) { |
1961 |
|
for (Runnable throwingAction : throwingActions) { |
1976 |
|
shouldThrow(expectedExceptionClass.getName()); |
1977 |
|
} |
1978 |
|
} |
1979 |
+ |
|
1980 |
+ |
public void assertIteratorExhausted(Iterator<?> it) { |
1981 |
+ |
try { |
1982 |
+ |
it.next(); |
1983 |
+ |
shouldThrow(); |
1984 |
+ |
} catch (NoSuchElementException success) {} |
1985 |
+ |
assertFalse(it.hasNext()); |
1986 |
+ |
} |
1987 |
+ |
|
1988 |
+ |
public <T> Callable<T> callableThrowing(final Exception ex) { |
1989 |
+ |
return new Callable<T>() { public T call() throws Exception { throw ex; }}; |
1990 |
+ |
} |
1991 |
+ |
|
1992 |
+ |
public Runnable runnableThrowing(final RuntimeException ex) { |
1993 |
+ |
return new Runnable() { public void run() { throw ex; }}; |
1994 |
+ |
} |
1995 |
+ |
|
1996 |
+ |
/** A reusable thread pool to be shared by tests. */ |
1997 |
+ |
static final ExecutorService cachedThreadPool = |
1998 |
+ |
new ThreadPoolExecutor(0, Integer.MAX_VALUE, |
1999 |
+ |
1000L, MILLISECONDS, |
2000 |
+ |
new SynchronousQueue<Runnable>()); |
2001 |
+ |
|
2002 |
+ |
static <T> void shuffle(T[] array) { |
2003 |
+ |
Collections.shuffle(Arrays.asList(array), ThreadLocalRandom.current()); |
2004 |
+ |
} |
2005 |
|
} |