1 |
|
/* |
2 |
< |
* Written by Doug Lea with assistance from members of JCP JSR-166 |
3 |
< |
* Expert Group and released to the public domain, as explained at |
4 |
< |
* http://creativecommons.org/licenses/publicdomain |
2 |
> |
* Written by Doug Lea and Martin Buchholz with assistance from |
3 |
> |
* members of JCP JSR-166 Expert Group and released to the public |
4 |
> |
* domain, as explained at |
5 |
> |
* http://creativecommons.org/publicdomain/zero/1.0/ |
6 |
|
* Other contributors include Andrew Wright, Jeffrey Hayes, |
7 |
|
* Pat Fisher, Mike Judd. |
8 |
|
*/ |
9 |
|
|
10 |
< |
import junit.framework.*; |
11 |
< |
import java.util.PropertyPermission; |
12 |
< |
import java.util.concurrent.*; |
13 |
< |
import java.util.concurrent.atomic.AtomicReference; |
10 |
> |
/* |
11 |
> |
* @test |
12 |
> |
* @summary JSR-166 tck tests, in a number of variations. |
13 |
> |
* The first is the conformance testing variant, |
14 |
> |
* while others also test implementation details. |
15 |
> |
* @build * |
16 |
> |
* @modules java.management |
17 |
> |
* @run junit/othervm/timeout=1000 JSR166TestCase |
18 |
> |
* @run junit/othervm/timeout=1000 |
19 |
> |
* --add-opens java.base/java.util.concurrent=ALL-UNNAMED |
20 |
> |
* --add-opens java.base/java.lang=ALL-UNNAMED |
21 |
> |
* -Djsr166.testImplementationDetails=true |
22 |
> |
* JSR166TestCase |
23 |
> |
* @run junit/othervm/timeout=1000 |
24 |
> |
* --add-opens java.base/java.util.concurrent=ALL-UNNAMED |
25 |
> |
* --add-opens java.base/java.lang=ALL-UNNAMED |
26 |
> |
* -Djsr166.testImplementationDetails=true |
27 |
> |
* -Djava.util.concurrent.ForkJoinPool.common.parallelism=0 |
28 |
> |
* JSR166TestCase |
29 |
> |
* @run junit/othervm/timeout=1000 |
30 |
> |
* --add-opens java.base/java.util.concurrent=ALL-UNNAMED |
31 |
> |
* --add-opens java.base/java.lang=ALL-UNNAMED |
32 |
> |
* -Djsr166.testImplementationDetails=true |
33 |
> |
* -Djava.util.concurrent.ForkJoinPool.common.parallelism=1 |
34 |
> |
* -Djava.util.secureRandomSeed=true |
35 |
> |
* JSR166TestCase |
36 |
> |
* @run junit/othervm/timeout=1000/policy=tck.policy |
37 |
> |
* --add-opens java.base/java.util.concurrent=ALL-UNNAMED |
38 |
> |
* --add-opens java.base/java.lang=ALL-UNNAMED |
39 |
> |
* -Djsr166.testImplementationDetails=true |
40 |
> |
* JSR166TestCase |
41 |
> |
*/ |
42 |
> |
|
43 |
|
import static java.util.concurrent.TimeUnit.MILLISECONDS; |
44 |
+ |
import static java.util.concurrent.TimeUnit.MINUTES; |
45 |
+ |
import static java.util.concurrent.TimeUnit.NANOSECONDS; |
46 |
+ |
|
47 |
+ |
import java.io.ByteArrayInputStream; |
48 |
+ |
import java.io.ByteArrayOutputStream; |
49 |
+ |
import java.io.ObjectInputStream; |
50 |
+ |
import java.io.ObjectOutputStream; |
51 |
+ |
import java.lang.management.ManagementFactory; |
52 |
+ |
import java.lang.management.ThreadInfo; |
53 |
+ |
import java.lang.management.ThreadMXBean; |
54 |
+ |
import java.lang.reflect.Constructor; |
55 |
+ |
import java.lang.reflect.Method; |
56 |
+ |
import java.lang.reflect.Modifier; |
57 |
|
import java.security.CodeSource; |
58 |
|
import java.security.Permission; |
59 |
|
import java.security.PermissionCollection; |
61 |
|
import java.security.Policy; |
62 |
|
import java.security.ProtectionDomain; |
63 |
|
import java.security.SecurityPermission; |
64 |
+ |
import java.util.ArrayList; |
65 |
+ |
import java.util.Arrays; |
66 |
+ |
import java.util.Collection; |
67 |
+ |
import java.util.Collections; |
68 |
+ |
import java.util.Date; |
69 |
+ |
import java.util.Deque; |
70 |
+ |
import java.util.Enumeration; |
71 |
+ |
import java.util.HashSet; |
72 |
+ |
import java.util.Iterator; |
73 |
+ |
import java.util.List; |
74 |
+ |
import java.util.NoSuchElementException; |
75 |
+ |
import java.util.PropertyPermission; |
76 |
+ |
import java.util.Set; |
77 |
+ |
import java.util.concurrent.BlockingQueue; |
78 |
+ |
import java.util.concurrent.Callable; |
79 |
+ |
import java.util.concurrent.CountDownLatch; |
80 |
+ |
import java.util.concurrent.CyclicBarrier; |
81 |
+ |
import java.util.concurrent.ExecutionException; |
82 |
+ |
import java.util.concurrent.Executor; |
83 |
+ |
import java.util.concurrent.Executors; |
84 |
+ |
import java.util.concurrent.ExecutorService; |
85 |
+ |
import java.util.concurrent.ForkJoinPool; |
86 |
+ |
import java.util.concurrent.Future; |
87 |
+ |
import java.util.concurrent.FutureTask; |
88 |
+ |
import java.util.concurrent.RecursiveAction; |
89 |
+ |
import java.util.concurrent.RecursiveTask; |
90 |
+ |
import java.util.concurrent.RejectedExecutionException; |
91 |
+ |
import java.util.concurrent.RejectedExecutionHandler; |
92 |
+ |
import java.util.concurrent.Semaphore; |
93 |
+ |
import java.util.concurrent.ScheduledExecutorService; |
94 |
+ |
import java.util.concurrent.ScheduledFuture; |
95 |
+ |
import java.util.concurrent.SynchronousQueue; |
96 |
+ |
import java.util.concurrent.ThreadFactory; |
97 |
+ |
import java.util.concurrent.ThreadLocalRandom; |
98 |
+ |
import java.util.concurrent.ThreadPoolExecutor; |
99 |
+ |
import java.util.concurrent.TimeUnit; |
100 |
+ |
import java.util.concurrent.TimeoutException; |
101 |
+ |
import java.util.concurrent.atomic.AtomicBoolean; |
102 |
+ |
import java.util.concurrent.atomic.AtomicReference; |
103 |
+ |
import java.util.regex.Pattern; |
104 |
+ |
|
105 |
+ |
import junit.framework.Test; |
106 |
+ |
import junit.framework.TestCase; |
107 |
+ |
import junit.framework.TestResult; |
108 |
+ |
import junit.framework.TestSuite; |
109 |
|
|
110 |
|
/** |
111 |
|
* Base class for JSR166 Junit TCK tests. Defines some constants, |
117 |
|
* |
118 |
|
* <ol> |
119 |
|
* |
120 |
< |
* <li> All assertions in code running in generated threads must use |
120 |
> |
* <li>All assertions in code running in generated threads must use |
121 |
|
* the forms {@link #threadFail}, {@link #threadAssertTrue}, {@link |
122 |
|
* #threadAssertEquals}, or {@link #threadAssertNull}, (not |
123 |
|
* {@code fail}, {@code assertTrue}, etc.) It is OK (but not |
124 |
|
* particularly recommended) for other code to use these forms too. |
125 |
|
* Only the most typically used JUnit assertion methods are defined |
126 |
< |
* this way, but enough to live with.</li> |
126 |
> |
* this way, but enough to live with. |
127 |
|
* |
128 |
< |
* <li> If you override {@link #setUp} or {@link #tearDown}, make sure |
128 |
> |
* <li>If you override {@link #setUp} or {@link #tearDown}, make sure |
129 |
|
* to invoke {@code super.setUp} and {@code super.tearDown} within |
130 |
|
* them. These methods are used to clear and check for thread |
131 |
< |
* assertion failures.</li> |
131 |
> |
* assertion failures. |
132 |
|
* |
133 |
|
* <li>All delays and timeouts must use one of the constants {@code |
134 |
|
* SHORT_DELAY_MS}, {@code SMALL_DELAY_MS}, {@code MEDIUM_DELAY_MS}, |
139 |
|
* is always discriminable as larger than SHORT and smaller than |
140 |
|
* MEDIUM. And so on. These constants are set to conservative values, |
141 |
|
* but even so, if there is ever any doubt, they can all be increased |
142 |
< |
* in one spot to rerun tests on slower platforms.</li> |
142 |
> |
* in one spot to rerun tests on slower platforms. |
143 |
|
* |
144 |
< |
* <li> All threads generated must be joined inside each test case |
144 |
> |
* <li>All threads generated must be joined inside each test case |
145 |
|
* method (or {@code fail} to do so) before returning from the |
146 |
|
* method. The {@code joinPool} method can be used to do this when |
147 |
< |
* using Executors.</li> |
147 |
> |
* using Executors. |
148 |
|
* |
149 |
|
* </ol> |
150 |
|
* |
151 |
< |
* <p> <b>Other notes</b> |
151 |
> |
* <p><b>Other notes</b> |
152 |
|
* <ul> |
153 |
|
* |
154 |
< |
* <li> Usually, there is one testcase method per JSR166 method |
154 |
> |
* <li>Usually, there is one testcase method per JSR166 method |
155 |
|
* covering "normal" operation, and then as many exception-testing |
156 |
|
* methods as there are exceptions the method can throw. Sometimes |
157 |
|
* there are multiple tests per JSR166 method when the different |
158 |
|
* "normal" behaviors differ significantly. And sometimes testcases |
159 |
< |
* cover multiple methods when they cannot be tested in |
72 |
< |
* isolation.</li> |
159 |
> |
* cover multiple methods when they cannot be tested in isolation. |
160 |
|
* |
161 |
< |
* <li> The documentation style for testcases is to provide as javadoc |
161 |
> |
* <li>The documentation style for testcases is to provide as javadoc |
162 |
|
* a simple sentence or two describing the property that the testcase |
163 |
|
* method purports to test. The javadocs do not say anything about how |
164 |
< |
* the property is tested. To find out, read the code.</li> |
164 |
> |
* the property is tested. To find out, read the code. |
165 |
|
* |
166 |
< |
* <li> These tests are "conformance tests", and do not attempt to |
166 |
> |
* <li>These tests are "conformance tests", and do not attempt to |
167 |
|
* test throughput, latency, scalability or other performance factors |
168 |
|
* (see the separate "jtreg" tests for a set intended to check these |
169 |
|
* for the most central aspects of functionality.) So, most tests use |
170 |
|
* the smallest sensible numbers of threads, collection sizes, etc |
171 |
< |
* needed to check basic conformance.</li> |
171 |
> |
* needed to check basic conformance. |
172 |
|
* |
173 |
|
* <li>The test classes currently do not declare inclusion in |
174 |
|
* any particular package to simplify things for people integrating |
175 |
< |
* them in TCK test suites.</li> |
175 |
> |
* them in TCK test suites. |
176 |
|
* |
177 |
< |
* <li> As a convenience, the {@code main} of this class (JSR166TestCase) |
178 |
< |
* runs all JSR166 unit tests.</li> |
177 |
> |
* <li>As a convenience, the {@code main} of this class (JSR166TestCase) |
178 |
> |
* runs all JSR166 unit tests. |
179 |
|
* |
180 |
|
* </ul> |
181 |
|
*/ |
187 |
|
Boolean.getBoolean("jsr166.expensiveTests"); |
188 |
|
|
189 |
|
/** |
190 |
+ |
* If true, also run tests that are not part of the official tck |
191 |
+ |
* because they test unspecified implementation details. |
192 |
+ |
*/ |
193 |
+ |
protected static final boolean testImplementationDetails = |
194 |
+ |
Boolean.getBoolean("jsr166.testImplementationDetails"); |
195 |
+ |
|
196 |
+ |
/** |
197 |
|
* If true, report on stdout all "slow" tests, that is, ones that |
198 |
|
* take more than profileThreshold milliseconds to execute. |
199 |
|
*/ |
207 |
|
private static final long profileThreshold = |
208 |
|
Long.getLong("jsr166.profileThreshold", 100); |
209 |
|
|
210 |
+ |
/** |
211 |
+ |
* The number of repetitions per test (for tickling rare bugs). |
212 |
+ |
*/ |
213 |
+ |
private static final int runsPerTest = |
214 |
+ |
Integer.getInteger("jsr166.runsPerTest", 1); |
215 |
+ |
|
216 |
+ |
/** |
217 |
+ |
* The number of repetitions of the test suite (for finding leaks?). |
218 |
+ |
*/ |
219 |
+ |
private static final int suiteRuns = |
220 |
+ |
Integer.getInteger("jsr166.suiteRuns", 1); |
221 |
+ |
|
222 |
+ |
/** |
223 |
+ |
* Returns the value of the system property, or NaN if not defined. |
224 |
+ |
*/ |
225 |
+ |
private static float systemPropertyValue(String name) { |
226 |
+ |
String floatString = System.getProperty(name); |
227 |
+ |
if (floatString == null) |
228 |
+ |
return Float.NaN; |
229 |
+ |
try { |
230 |
+ |
return Float.parseFloat(floatString); |
231 |
+ |
} catch (NumberFormatException ex) { |
232 |
+ |
throw new IllegalArgumentException( |
233 |
+ |
String.format("Bad float value in system property %s=%s", |
234 |
+ |
name, floatString)); |
235 |
+ |
} |
236 |
+ |
} |
237 |
+ |
|
238 |
+ |
/** |
239 |
+ |
* The scaling factor to apply to standard delays used in tests. |
240 |
+ |
* May be initialized from any of: |
241 |
+ |
* - the "jsr166.delay.factor" system property |
242 |
+ |
* - the "test.timeout.factor" system property (as used by jtreg) |
243 |
+ |
* See: http://openjdk.java.net/jtreg/tag-spec.html |
244 |
+ |
* - hard-coded fuzz factor when using a known slowpoke VM |
245 |
+ |
*/ |
246 |
+ |
private static final float delayFactor = delayFactor(); |
247 |
+ |
|
248 |
+ |
private static float delayFactor() { |
249 |
+ |
float x; |
250 |
+ |
if (!Float.isNaN(x = systemPropertyValue("jsr166.delay.factor"))) |
251 |
+ |
return x; |
252 |
+ |
if (!Float.isNaN(x = systemPropertyValue("test.timeout.factor"))) |
253 |
+ |
return x; |
254 |
+ |
String prop = System.getProperty("java.vm.version"); |
255 |
+ |
if (prop != null && prop.matches(".*debug.*")) |
256 |
+ |
return 4.0f; // How much slower is fastdebug than product?! |
257 |
+ |
return 1.0f; |
258 |
+ |
} |
259 |
+ |
|
260 |
+ |
public JSR166TestCase() { super(); } |
261 |
+ |
public JSR166TestCase(String name) { super(name); } |
262 |
+ |
|
263 |
+ |
/** |
264 |
+ |
* A filter for tests to run, matching strings of the form |
265 |
+ |
* methodName(className), e.g. "testInvokeAll5(ForkJoinPoolTest)" |
266 |
+ |
* Usefully combined with jsr166.runsPerTest. |
267 |
+ |
*/ |
268 |
+ |
private static final Pattern methodFilter = methodFilter(); |
269 |
+ |
|
270 |
+ |
private static Pattern methodFilter() { |
271 |
+ |
String regex = System.getProperty("jsr166.methodFilter"); |
272 |
+ |
return (regex == null) ? null : Pattern.compile(regex); |
273 |
+ |
} |
274 |
+ |
|
275 |
+ |
// Instrumentation to debug very rare, but very annoying hung test runs. |
276 |
+ |
static volatile TestCase currentTestCase; |
277 |
+ |
// static volatile int currentRun = 0; |
278 |
+ |
static { |
279 |
+ |
Runnable checkForWedgedTest = new Runnable() { public void run() { |
280 |
+ |
// Avoid spurious reports with enormous runsPerTest. |
281 |
+ |
// A single test case run should never take more than 1 second. |
282 |
+ |
// But let's cap it at the high end too ... |
283 |
+ |
final int timeoutMinutes = |
284 |
+ |
Math.min(15, Math.max(runsPerTest / 60, 1)); |
285 |
+ |
for (TestCase lastTestCase = currentTestCase;;) { |
286 |
+ |
try { MINUTES.sleep(timeoutMinutes); } |
287 |
+ |
catch (InterruptedException unexpected) { break; } |
288 |
+ |
if (lastTestCase == currentTestCase) { |
289 |
+ |
System.err.printf( |
290 |
+ |
"Looks like we're stuck running test: %s%n", |
291 |
+ |
lastTestCase); |
292 |
+ |
// System.err.printf( |
293 |
+ |
// "Looks like we're stuck running test: %s (%d/%d)%n", |
294 |
+ |
// lastTestCase, currentRun, runsPerTest); |
295 |
+ |
// System.err.println("availableProcessors=" + |
296 |
+ |
// Runtime.getRuntime().availableProcessors()); |
297 |
+ |
// System.err.printf("cpu model = %s%n", cpuModel()); |
298 |
+ |
dumpTestThreads(); |
299 |
+ |
// one stack dump is probably enough; more would be spam |
300 |
+ |
break; |
301 |
+ |
} |
302 |
+ |
lastTestCase = currentTestCase; |
303 |
+ |
}}}; |
304 |
+ |
Thread thread = new Thread(checkForWedgedTest, "checkForWedgedTest"); |
305 |
+ |
thread.setDaemon(true); |
306 |
+ |
thread.start(); |
307 |
+ |
} |
308 |
+ |
|
309 |
+ |
// public static String cpuModel() { |
310 |
+ |
// try { |
311 |
+ |
// java.util.regex.Matcher matcher |
312 |
+ |
// = Pattern.compile("model name\\s*: (.*)") |
313 |
+ |
// .matcher(new String( |
314 |
+ |
// java.nio.file.Files.readAllBytes( |
315 |
+ |
// java.nio.file.Paths.get("/proc/cpuinfo")), "UTF-8")); |
316 |
+ |
// matcher.find(); |
317 |
+ |
// return matcher.group(1); |
318 |
+ |
// } catch (Exception ex) { return null; } |
319 |
+ |
// } |
320 |
+ |
|
321 |
+ |
public void runBare() throws Throwable { |
322 |
+ |
currentTestCase = this; |
323 |
+ |
if (methodFilter == null |
324 |
+ |
|| methodFilter.matcher(toString()).find()) |
325 |
+ |
super.runBare(); |
326 |
+ |
} |
327 |
+ |
|
328 |
|
protected void runTest() throws Throwable { |
329 |
< |
if (profileTests) |
330 |
< |
runTestProfiled(); |
331 |
< |
else |
332 |
< |
super.runTest(); |
329 |
> |
for (int i = 0; i < runsPerTest; i++) { |
330 |
> |
// currentRun = i; |
331 |
> |
if (profileTests) |
332 |
> |
runTestProfiled(); |
333 |
> |
else |
334 |
> |
super.runTest(); |
335 |
> |
} |
336 |
|
} |
337 |
|
|
338 |
|
protected void runTestProfiled() throws Throwable { |
339 |
< |
long t0 = System.nanoTime(); |
340 |
< |
try { |
339 |
> |
for (int i = 0; i < 2; i++) { |
340 |
> |
long startTime = System.nanoTime(); |
341 |
|
super.runTest(); |
342 |
< |
} finally { |
343 |
< |
long elapsedMillis = |
344 |
< |
(System.nanoTime() - t0) / (1000L * 1000L); |
345 |
< |
if (elapsedMillis >= profileThreshold) |
342 |
> |
long elapsedMillis = millisElapsedSince(startTime); |
343 |
> |
if (elapsedMillis < profileThreshold) |
344 |
> |
break; |
345 |
> |
// Never report first run of any test; treat it as a |
346 |
> |
// warmup run, notably to trigger all needed classloading, |
347 |
> |
if (i > 0) |
348 |
|
System.out.printf("%n%s: %d%n", toString(), elapsedMillis); |
349 |
|
} |
350 |
|
} |
351 |
|
|
352 |
|
/** |
353 |
< |
* Runs all JSR166 unit tests using junit.textui.TestRunner |
353 |
> |
* Runs all JSR166 unit tests using junit.textui.TestRunner. |
354 |
|
*/ |
355 |
|
public static void main(String[] args) { |
356 |
+ |
main(suite(), args); |
357 |
+ |
} |
358 |
+ |
|
359 |
+ |
static class PithyResultPrinter extends junit.textui.ResultPrinter { |
360 |
+ |
PithyResultPrinter(java.io.PrintStream writer) { super(writer); } |
361 |
+ |
long runTime; |
362 |
+ |
public void startTest(Test test) {} |
363 |
+ |
protected void printHeader(long runTime) { |
364 |
+ |
this.runTime = runTime; // defer printing for later |
365 |
+ |
} |
366 |
+ |
protected void printFooter(TestResult result) { |
367 |
+ |
if (result.wasSuccessful()) { |
368 |
+ |
getWriter().println("OK (" + result.runCount() + " tests)" |
369 |
+ |
+ " Time: " + elapsedTimeAsString(runTime)); |
370 |
+ |
} else { |
371 |
+ |
getWriter().println("Time: " + elapsedTimeAsString(runTime)); |
372 |
+ |
super.printFooter(result); |
373 |
+ |
} |
374 |
+ |
} |
375 |
+ |
} |
376 |
+ |
|
377 |
+ |
/** |
378 |
+ |
* Returns a TestRunner that doesn't bother with unnecessary |
379 |
+ |
* fluff, like printing a "." for each test case. |
380 |
+ |
*/ |
381 |
+ |
static junit.textui.TestRunner newPithyTestRunner() { |
382 |
+ |
junit.textui.TestRunner runner = new junit.textui.TestRunner(); |
383 |
+ |
runner.setPrinter(new PithyResultPrinter(System.out)); |
384 |
+ |
return runner; |
385 |
+ |
} |
386 |
+ |
|
387 |
+ |
/** |
388 |
+ |
* Runs all unit tests in the given test suite. |
389 |
+ |
* Actual behavior influenced by jsr166.* system properties. |
390 |
+ |
*/ |
391 |
+ |
static void main(Test suite, String[] args) { |
392 |
|
if (useSecurityManager) { |
393 |
|
System.err.println("Setting a permissive security manager"); |
394 |
|
Policy.setPolicy(permissivePolicy()); |
395 |
|
System.setSecurityManager(new SecurityManager()); |
396 |
|
} |
397 |
< |
int iters = (args.length == 0) ? 1 : Integer.parseInt(args[0]); |
398 |
< |
|
399 |
< |
Test s = suite(); |
400 |
< |
for (int i = 0; i < iters; ++i) { |
148 |
< |
junit.textui.TestRunner.run(s); |
397 |
> |
for (int i = 0; i < suiteRuns; i++) { |
398 |
> |
TestResult result = newPithyTestRunner().doRun(suite); |
399 |
> |
if (!result.wasSuccessful()) |
400 |
> |
System.exit(1); |
401 |
|
System.gc(); |
402 |
|
System.runFinalization(); |
403 |
|
} |
152 |
– |
System.exit(0); |
404 |
|
} |
405 |
|
|
406 |
|
public static TestSuite newTestSuite(Object... suiteOrClasses) { |
416 |
|
return suite; |
417 |
|
} |
418 |
|
|
419 |
+ |
public static void addNamedTestClasses(TestSuite suite, |
420 |
+ |
String... testClassNames) { |
421 |
+ |
for (String testClassName : testClassNames) { |
422 |
+ |
try { |
423 |
+ |
Class<?> testClass = Class.forName(testClassName); |
424 |
+ |
Method m = testClass.getDeclaredMethod("suite"); |
425 |
+ |
suite.addTest(newTestSuite((Test)m.invoke(null))); |
426 |
+ |
} catch (ReflectiveOperationException e) { |
427 |
+ |
throw new AssertionError("Missing test class", e); |
428 |
+ |
} |
429 |
+ |
} |
430 |
+ |
} |
431 |
+ |
|
432 |
+ |
public static final double JAVA_CLASS_VERSION; |
433 |
+ |
public static final String JAVA_SPECIFICATION_VERSION; |
434 |
+ |
static { |
435 |
+ |
try { |
436 |
+ |
JAVA_CLASS_VERSION = java.security.AccessController.doPrivileged( |
437 |
+ |
new java.security.PrivilegedAction<Double>() { |
438 |
+ |
public Double run() { |
439 |
+ |
return Double.valueOf(System.getProperty("java.class.version"));}}); |
440 |
+ |
JAVA_SPECIFICATION_VERSION = java.security.AccessController.doPrivileged( |
441 |
+ |
new java.security.PrivilegedAction<String>() { |
442 |
+ |
public String run() { |
443 |
+ |
return System.getProperty("java.specification.version");}}); |
444 |
+ |
} catch (Throwable t) { |
445 |
+ |
throw new Error(t); |
446 |
+ |
} |
447 |
+ |
} |
448 |
+ |
|
449 |
+ |
public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; } |
450 |
+ |
public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; } |
451 |
+ |
public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; } |
452 |
+ |
public static boolean atLeastJava9() { return JAVA_CLASS_VERSION >= 53.0; } |
453 |
+ |
public static boolean atLeastJava10() { return JAVA_CLASS_VERSION >= 54.0; } |
454 |
+ |
public static boolean atLeastJava11() { return JAVA_CLASS_VERSION >= 55.0; } |
455 |
+ |
|
456 |
|
/** |
457 |
|
* Collects all JSR166 unit tests as one suite. |
458 |
|
*/ |
459 |
|
public static Test suite() { |
460 |
< |
return newTestSuite( |
460 |
> |
// Java7+ test classes |
461 |
> |
TestSuite suite = newTestSuite( |
462 |
|
ForkJoinPoolTest.suite(), |
463 |
|
ForkJoinTaskTest.suite(), |
464 |
|
RecursiveActionTest.suite(), |
472 |
|
AbstractQueuedLongSynchronizerTest.suite(), |
473 |
|
ArrayBlockingQueueTest.suite(), |
474 |
|
ArrayDequeTest.suite(), |
475 |
+ |
ArrayListTest.suite(), |
476 |
|
AtomicBooleanTest.suite(), |
477 |
|
AtomicIntegerArrayTest.suite(), |
478 |
|
AtomicIntegerFieldUpdaterTest.suite(), |
495 |
|
CopyOnWriteArrayListTest.suite(), |
496 |
|
CopyOnWriteArraySetTest.suite(), |
497 |
|
CountDownLatchTest.suite(), |
498 |
+ |
CountedCompleterTest.suite(), |
499 |
|
CyclicBarrierTest.suite(), |
500 |
|
DelayQueueTest.suite(), |
501 |
|
EntryTest.suite(), |
524 |
|
TreeMapTest.suite(), |
525 |
|
TreeSetTest.suite(), |
526 |
|
TreeSubMapTest.suite(), |
527 |
< |
TreeSubSetTest.suite()); |
527 |
> |
TreeSubSetTest.suite(), |
528 |
> |
VectorTest.suite()); |
529 |
> |
|
530 |
> |
// Java8+ test classes |
531 |
> |
if (atLeastJava8()) { |
532 |
> |
String[] java8TestClassNames = { |
533 |
> |
"ArrayDeque8Test", |
534 |
> |
"Atomic8Test", |
535 |
> |
"CompletableFutureTest", |
536 |
> |
"ConcurrentHashMap8Test", |
537 |
> |
"CountedCompleter8Test", |
538 |
> |
"DoubleAccumulatorTest", |
539 |
> |
"DoubleAdderTest", |
540 |
> |
"ForkJoinPool8Test", |
541 |
> |
"ForkJoinTask8Test", |
542 |
> |
"HashMapTest", |
543 |
> |
"LinkedBlockingDeque8Test", |
544 |
> |
"LinkedBlockingQueue8Test", |
545 |
> |
"LongAccumulatorTest", |
546 |
> |
"LongAdderTest", |
547 |
> |
"SplittableRandomTest", |
548 |
> |
"StampedLockTest", |
549 |
> |
"SubmissionPublisherTest", |
550 |
> |
"ThreadLocalRandom8Test", |
551 |
> |
"TimeUnit8Test", |
552 |
> |
}; |
553 |
> |
addNamedTestClasses(suite, java8TestClassNames); |
554 |
> |
} |
555 |
> |
|
556 |
> |
// Java9+ test classes |
557 |
> |
if (atLeastJava9()) { |
558 |
> |
String[] java9TestClassNames = { |
559 |
> |
"AtomicBoolean9Test", |
560 |
> |
"AtomicInteger9Test", |
561 |
> |
"AtomicIntegerArray9Test", |
562 |
> |
"AtomicLong9Test", |
563 |
> |
"AtomicLongArray9Test", |
564 |
> |
"AtomicReference9Test", |
565 |
> |
"AtomicReferenceArray9Test", |
566 |
> |
"ExecutorCompletionService9Test", |
567 |
> |
"ForkJoinPool9Test", |
568 |
> |
}; |
569 |
> |
addNamedTestClasses(suite, java9TestClassNames); |
570 |
> |
} |
571 |
> |
|
572 |
> |
return suite; |
573 |
|
} |
574 |
|
|
575 |
+ |
/** Returns list of junit-style test method names in given class. */ |
576 |
+ |
public static ArrayList<String> testMethodNames(Class<?> testClass) { |
577 |
+ |
Method[] methods = testClass.getDeclaredMethods(); |
578 |
+ |
ArrayList<String> names = new ArrayList<>(methods.length); |
579 |
+ |
for (Method method : methods) { |
580 |
+ |
if (method.getName().startsWith("test") |
581 |
+ |
&& Modifier.isPublic(method.getModifiers()) |
582 |
+ |
// method.getParameterCount() requires jdk8+ |
583 |
+ |
&& method.getParameterTypes().length == 0) { |
584 |
+ |
names.add(method.getName()); |
585 |
+ |
} |
586 |
+ |
} |
587 |
+ |
return names; |
588 |
+ |
} |
589 |
+ |
|
590 |
+ |
/** |
591 |
+ |
* Returns junit-style testSuite for the given test class, but |
592 |
+ |
* parameterized by passing extra data to each test. |
593 |
+ |
*/ |
594 |
+ |
public static <ExtraData> Test parameterizedTestSuite |
595 |
+ |
(Class<? extends JSR166TestCase> testClass, |
596 |
+ |
Class<ExtraData> dataClass, |
597 |
+ |
ExtraData data) { |
598 |
+ |
try { |
599 |
+ |
TestSuite suite = new TestSuite(); |
600 |
+ |
Constructor c = |
601 |
+ |
testClass.getDeclaredConstructor(dataClass, String.class); |
602 |
+ |
for (String methodName : testMethodNames(testClass)) |
603 |
+ |
suite.addTest((Test) c.newInstance(data, methodName)); |
604 |
+ |
return suite; |
605 |
+ |
} catch (ReflectiveOperationException e) { |
606 |
+ |
throw new AssertionError(e); |
607 |
+ |
} |
608 |
+ |
} |
609 |
+ |
|
610 |
+ |
/** |
611 |
+ |
* Returns junit-style testSuite for the jdk8 extension of the |
612 |
+ |
* given test class, but parameterized by passing extra data to |
613 |
+ |
* each test. Uses reflection to allow compilation in jdk7. |
614 |
+ |
*/ |
615 |
+ |
public static <ExtraData> Test jdk8ParameterizedTestSuite |
616 |
+ |
(Class<? extends JSR166TestCase> testClass, |
617 |
+ |
Class<ExtraData> dataClass, |
618 |
+ |
ExtraData data) { |
619 |
+ |
if (atLeastJava8()) { |
620 |
+ |
String name = testClass.getName(); |
621 |
+ |
String name8 = name.replaceAll("Test$", "8Test"); |
622 |
+ |
if (name.equals(name8)) throw new AssertionError(name); |
623 |
+ |
try { |
624 |
+ |
return (Test) |
625 |
+ |
Class.forName(name8) |
626 |
+ |
.getMethod("testSuite", dataClass) |
627 |
+ |
.invoke(null, data); |
628 |
+ |
} catch (ReflectiveOperationException e) { |
629 |
+ |
throw new AssertionError(e); |
630 |
+ |
} |
631 |
+ |
} else { |
632 |
+ |
return new TestSuite(); |
633 |
+ |
} |
634 |
+ |
} |
635 |
+ |
|
636 |
+ |
// Delays for timing-dependent tests, in milliseconds. |
637 |
|
|
638 |
|
public static long SHORT_DELAY_MS; |
639 |
|
public static long SMALL_DELAY_MS; |
640 |
|
public static long MEDIUM_DELAY_MS; |
641 |
|
public static long LONG_DELAY_MS; |
642 |
|
|
643 |
+ |
private static final long RANDOM_TIMEOUT; |
644 |
+ |
private static final long RANDOM_EXPIRED_TIMEOUT; |
645 |
+ |
private static final TimeUnit RANDOM_TIMEUNIT; |
646 |
+ |
static { |
647 |
+ |
ThreadLocalRandom rnd = ThreadLocalRandom.current(); |
648 |
+ |
long[] timeouts = { Long.MIN_VALUE, -1, 0, 1, Long.MAX_VALUE }; |
649 |
+ |
RANDOM_TIMEOUT = timeouts[rnd.nextInt(timeouts.length)]; |
650 |
+ |
RANDOM_EXPIRED_TIMEOUT = timeouts[rnd.nextInt(3)]; |
651 |
+ |
TimeUnit[] timeUnits = TimeUnit.values(); |
652 |
+ |
RANDOM_TIMEUNIT = timeUnits[rnd.nextInt(timeUnits.length)]; |
653 |
+ |
} |
654 |
|
|
655 |
|
/** |
656 |
< |
* Returns the shortest timed delay. This could |
657 |
< |
* be reimplemented to use for example a Property. |
656 |
> |
* Returns a timeout for use when any value at all will do. |
657 |
> |
*/ |
658 |
> |
static long randomTimeout() { return RANDOM_TIMEOUT; } |
659 |
> |
|
660 |
> |
/** |
661 |
> |
* Returns a timeout that means "no waiting", i.e. not positive. |
662 |
> |
*/ |
663 |
> |
static long randomExpiredTimeout() { return RANDOM_EXPIRED_TIMEOUT; } |
664 |
> |
|
665 |
> |
/** |
666 |
> |
* Returns a random non-null TimeUnit. |
667 |
> |
*/ |
668 |
> |
static TimeUnit randomTimeUnit() { return RANDOM_TIMEUNIT; } |
669 |
> |
|
670 |
> |
/** |
671 |
> |
* Returns the shortest timed delay. This can be scaled up for |
672 |
> |
* slow machines using the jsr166.delay.factor system property, |
673 |
> |
* or via jtreg's -timeoutFactor: flag. |
674 |
> |
* http://openjdk.java.net/jtreg/command-help.html |
675 |
|
*/ |
676 |
|
protected long getShortDelay() { |
677 |
< |
return 50; |
677 |
> |
return (long) (50 * delayFactor); |
678 |
|
} |
679 |
|
|
254 |
– |
|
680 |
|
/** |
681 |
|
* Sets delays as multiples of SHORT_DELAY. |
682 |
|
*/ |
684 |
|
SHORT_DELAY_MS = getShortDelay(); |
685 |
|
SMALL_DELAY_MS = SHORT_DELAY_MS * 5; |
686 |
|
MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10; |
687 |
< |
LONG_DELAY_MS = SHORT_DELAY_MS * 50; |
687 |
> |
LONG_DELAY_MS = SHORT_DELAY_MS * 200; |
688 |
> |
} |
689 |
> |
|
690 |
> |
private static final long TIMEOUT_DELAY_MS |
691 |
> |
= (long) (12.0 * Math.cbrt(delayFactor)); |
692 |
> |
|
693 |
> |
/** |
694 |
> |
* Returns a timeout in milliseconds to be used in tests that verify |
695 |
> |
* that operations block or time out. We want this to be longer |
696 |
> |
* than the OS scheduling quantum, but not too long, so don't scale |
697 |
> |
* linearly with delayFactor; we use "crazy" cube root instead. |
698 |
> |
*/ |
699 |
> |
static long timeoutMillis() { |
700 |
> |
return TIMEOUT_DELAY_MS; |
701 |
> |
} |
702 |
> |
|
703 |
> |
/** |
704 |
> |
* Returns a new Date instance representing a time at least |
705 |
> |
* delayMillis milliseconds in the future. |
706 |
> |
*/ |
707 |
> |
Date delayedDate(long delayMillis) { |
708 |
> |
// Add 1 because currentTimeMillis is known to round into the past. |
709 |
> |
return new Date(System.currentTimeMillis() + delayMillis + 1); |
710 |
|
} |
711 |
|
|
712 |
|
/** |
713 |
|
* The first exception encountered if any threadAssertXXX method fails. |
714 |
|
*/ |
715 |
|
private final AtomicReference<Throwable> threadFailure |
716 |
< |
= new AtomicReference<Throwable>(null); |
716 |
> |
= new AtomicReference<>(null); |
717 |
|
|
718 |
|
/** |
719 |
|
* Records an exception so that it can be rethrown later in the test |
722 |
|
* the same test have no effect. |
723 |
|
*/ |
724 |
|
public void threadRecordFailure(Throwable t) { |
725 |
+ |
System.err.println(t); |
726 |
+ |
dumpTestThreads(); |
727 |
|
threadFailure.compareAndSet(null, t); |
728 |
|
} |
729 |
|
|
731 |
|
setDelays(); |
732 |
|
} |
733 |
|
|
734 |
+ |
void tearDownFail(String format, Object... args) { |
735 |
+ |
String msg = toString() + ": " + String.format(format, args); |
736 |
+ |
System.err.println(msg); |
737 |
+ |
dumpTestThreads(); |
738 |
+ |
throw new AssertionError(msg); |
739 |
+ |
} |
740 |
+ |
|
741 |
|
/** |
742 |
+ |
* Extra checks that get done for all test cases. |
743 |
+ |
* |
744 |
|
* Triggers test case failure if any thread assertions have failed, |
745 |
|
* by rethrowing, in the test harness thread, any exception recorded |
746 |
|
* earlier by threadRecordFailure. |
747 |
+ |
* |
748 |
+ |
* Triggers test case failure if interrupt status is set in the main thread. |
749 |
|
*/ |
750 |
|
public void tearDown() throws Exception { |
751 |
< |
Throwable t = threadFailure.get(); |
751 |
> |
Throwable t = threadFailure.getAndSet(null); |
752 |
|
if (t != null) { |
753 |
|
if (t instanceof Error) |
754 |
|
throw (Error) t; |
756 |
|
throw (RuntimeException) t; |
757 |
|
else if (t instanceof Exception) |
758 |
|
throw (Exception) t; |
759 |
< |
else { |
760 |
< |
AssertionFailedError afe = |
761 |
< |
new AssertionFailedError(t.toString()); |
762 |
< |
afe.initCause(t); |
763 |
< |
throw afe; |
759 |
> |
else |
760 |
> |
throw new AssertionError(t.toString(), t); |
761 |
> |
} |
762 |
> |
|
763 |
> |
if (Thread.interrupted()) |
764 |
> |
tearDownFail("interrupt status set in main thread"); |
765 |
> |
|
766 |
> |
checkForkJoinPoolThreadLeaks(); |
767 |
> |
} |
768 |
> |
|
769 |
> |
/** |
770 |
> |
* Finds missing PoolCleaners |
771 |
> |
*/ |
772 |
> |
void checkForkJoinPoolThreadLeaks() throws InterruptedException { |
773 |
> |
Thread[] survivors = new Thread[7]; |
774 |
> |
int count = Thread.enumerate(survivors); |
775 |
> |
for (int i = 0; i < count; i++) { |
776 |
> |
Thread thread = survivors[i]; |
777 |
> |
String name = thread.getName(); |
778 |
> |
if (name.startsWith("ForkJoinPool-")) { |
779 |
> |
// give thread some time to terminate |
780 |
> |
thread.join(LONG_DELAY_MS); |
781 |
> |
if (thread.isAlive()) |
782 |
> |
tearDownFail("Found leaked ForkJoinPool thread thread=%s", |
783 |
> |
thread); |
784 |
|
} |
785 |
|
} |
786 |
+ |
|
787 |
+ |
if (!ForkJoinPool.commonPool() |
788 |
+ |
.awaitQuiescence(LONG_DELAY_MS, MILLISECONDS)) |
789 |
+ |
tearDownFail("ForkJoin common pool thread stuck"); |
790 |
|
} |
791 |
|
|
792 |
|
/** |
793 |
|
* Just like fail(reason), but additionally recording (using |
794 |
< |
* threadRecordFailure) any AssertionFailedError thrown, so that |
795 |
< |
* the current testcase will fail. |
794 |
> |
* threadRecordFailure) any AssertionError thrown, so that the |
795 |
> |
* current testcase will fail. |
796 |
|
*/ |
797 |
|
public void threadFail(String reason) { |
798 |
|
try { |
799 |
|
fail(reason); |
800 |
< |
} catch (AssertionFailedError t) { |
801 |
< |
threadRecordFailure(t); |
802 |
< |
fail(reason); |
800 |
> |
} catch (AssertionError fail) { |
801 |
> |
threadRecordFailure(fail); |
802 |
> |
throw fail; |
803 |
|
} |
804 |
|
} |
805 |
|
|
806 |
|
/** |
807 |
|
* Just like assertTrue(b), but additionally recording (using |
808 |
< |
* threadRecordFailure) any AssertionFailedError thrown, so that |
809 |
< |
* the current testcase will fail. |
808 |
> |
* threadRecordFailure) any AssertionError thrown, so that the |
809 |
> |
* current testcase will fail. |
810 |
|
*/ |
811 |
|
public void threadAssertTrue(boolean b) { |
812 |
|
try { |
813 |
|
assertTrue(b); |
814 |
< |
} catch (AssertionFailedError t) { |
815 |
< |
threadRecordFailure(t); |
816 |
< |
throw t; |
814 |
> |
} catch (AssertionError fail) { |
815 |
> |
threadRecordFailure(fail); |
816 |
> |
throw fail; |
817 |
|
} |
818 |
|
} |
819 |
|
|
820 |
|
/** |
821 |
|
* Just like assertFalse(b), but additionally recording (using |
822 |
< |
* threadRecordFailure) any AssertionFailedError thrown, so that |
823 |
< |
* the current testcase will fail. |
822 |
> |
* threadRecordFailure) any AssertionError thrown, so that the |
823 |
> |
* current testcase will fail. |
824 |
|
*/ |
825 |
|
public void threadAssertFalse(boolean b) { |
826 |
|
try { |
827 |
|
assertFalse(b); |
828 |
< |
} catch (AssertionFailedError t) { |
829 |
< |
threadRecordFailure(t); |
830 |
< |
throw t; |
828 |
> |
} catch (AssertionError fail) { |
829 |
> |
threadRecordFailure(fail); |
830 |
> |
throw fail; |
831 |
|
} |
832 |
|
} |
833 |
|
|
834 |
|
/** |
835 |
|
* Just like assertNull(x), but additionally recording (using |
836 |
< |
* threadRecordFailure) any AssertionFailedError thrown, so that |
837 |
< |
* the current testcase will fail. |
836 |
> |
* threadRecordFailure) any AssertionError thrown, so that the |
837 |
> |
* current testcase will fail. |
838 |
|
*/ |
839 |
|
public void threadAssertNull(Object x) { |
840 |
|
try { |
841 |
|
assertNull(x); |
842 |
< |
} catch (AssertionFailedError t) { |
843 |
< |
threadRecordFailure(t); |
844 |
< |
throw t; |
842 |
> |
} catch (AssertionError fail) { |
843 |
> |
threadRecordFailure(fail); |
844 |
> |
throw fail; |
845 |
|
} |
846 |
|
} |
847 |
|
|
848 |
|
/** |
849 |
|
* Just like assertEquals(x, y), but additionally recording (using |
850 |
< |
* threadRecordFailure) any AssertionFailedError thrown, so that |
851 |
< |
* the current testcase will fail. |
850 |
> |
* threadRecordFailure) any AssertionError thrown, so that the |
851 |
> |
* current testcase will fail. |
852 |
|
*/ |
853 |
|
public void threadAssertEquals(long x, long y) { |
854 |
|
try { |
855 |
|
assertEquals(x, y); |
856 |
< |
} catch (AssertionFailedError t) { |
857 |
< |
threadRecordFailure(t); |
858 |
< |
throw t; |
856 |
> |
} catch (AssertionError fail) { |
857 |
> |
threadRecordFailure(fail); |
858 |
> |
throw fail; |
859 |
|
} |
860 |
|
} |
861 |
|
|
862 |
|
/** |
863 |
|
* Just like assertEquals(x, y), but additionally recording (using |
864 |
< |
* threadRecordFailure) any AssertionFailedError thrown, so that |
865 |
< |
* the current testcase will fail. |
864 |
> |
* threadRecordFailure) any AssertionError thrown, so that the |
865 |
> |
* current testcase will fail. |
866 |
|
*/ |
867 |
|
public void threadAssertEquals(Object x, Object y) { |
868 |
|
try { |
869 |
|
assertEquals(x, y); |
870 |
< |
} catch (AssertionFailedError t) { |
871 |
< |
threadRecordFailure(t); |
872 |
< |
throw t; |
873 |
< |
} catch (Throwable t) { |
874 |
< |
threadUnexpectedException(t); |
870 |
> |
} catch (AssertionError fail) { |
871 |
> |
threadRecordFailure(fail); |
872 |
> |
throw fail; |
873 |
> |
} catch (Throwable fail) { |
874 |
> |
threadUnexpectedException(fail); |
875 |
|
} |
876 |
|
} |
877 |
|
|
878 |
|
/** |
879 |
|
* Just like assertSame(x, y), but additionally recording (using |
880 |
< |
* threadRecordFailure) any AssertionFailedError thrown, so that |
881 |
< |
* the current testcase will fail. |
880 |
> |
* threadRecordFailure) any AssertionError thrown, so that the |
881 |
> |
* current testcase will fail. |
882 |
|
*/ |
883 |
|
public void threadAssertSame(Object x, Object y) { |
884 |
|
try { |
885 |
|
assertSame(x, y); |
886 |
< |
} catch (AssertionFailedError t) { |
887 |
< |
threadRecordFailure(t); |
888 |
< |
throw t; |
886 |
> |
} catch (AssertionError fail) { |
887 |
> |
threadRecordFailure(fail); |
888 |
> |
throw fail; |
889 |
|
} |
890 |
|
} |
891 |
|
|
905 |
|
|
906 |
|
/** |
907 |
|
* Records the given exception using {@link #threadRecordFailure}, |
908 |
< |
* then rethrows the exception, wrapping it in an |
909 |
< |
* AssertionFailedError if necessary. |
908 |
> |
* then rethrows the exception, wrapping it in an AssertionError |
909 |
> |
* if necessary. |
910 |
|
*/ |
911 |
|
public void threadUnexpectedException(Throwable t) { |
912 |
|
threadRecordFailure(t); |
915 |
|
throw (RuntimeException) t; |
916 |
|
else if (t instanceof Error) |
917 |
|
throw (Error) t; |
918 |
< |
else { |
919 |
< |
AssertionFailedError afe = |
920 |
< |
new AssertionFailedError("unexpected exception: " + t); |
921 |
< |
t.initCause(t); |
922 |
< |
throw afe; |
918 |
> |
else |
919 |
> |
throw new AssertionError("unexpected exception: " + t, t); |
920 |
> |
} |
921 |
> |
|
922 |
> |
/** |
923 |
> |
* Delays, via Thread.sleep, for the given millisecond delay, but |
924 |
> |
* if the sleep is shorter than specified, may re-sleep or yield |
925 |
> |
* until time elapses. Ensures that the given time, as measured |
926 |
> |
* by System.nanoTime(), has elapsed. |
927 |
> |
*/ |
928 |
> |
static void delay(long millis) throws InterruptedException { |
929 |
> |
long nanos = millis * (1000 * 1000); |
930 |
> |
final long wakeupTime = System.nanoTime() + nanos; |
931 |
> |
do { |
932 |
> |
if (millis > 0L) |
933 |
> |
Thread.sleep(millis); |
934 |
> |
else // too short to sleep |
935 |
> |
Thread.yield(); |
936 |
> |
nanos = wakeupTime - System.nanoTime(); |
937 |
> |
millis = nanos / (1000 * 1000); |
938 |
> |
} while (nanos >= 0L); |
939 |
> |
} |
940 |
> |
|
941 |
> |
/** |
942 |
> |
* Allows use of try-with-resources with per-test thread pools. |
943 |
> |
*/ |
944 |
> |
class PoolCleaner implements AutoCloseable { |
945 |
> |
private final ExecutorService pool; |
946 |
> |
public PoolCleaner(ExecutorService pool) { this.pool = pool; } |
947 |
> |
public void close() { joinPool(pool); } |
948 |
> |
} |
949 |
> |
|
950 |
> |
/** |
951 |
> |
* An extension of PoolCleaner that has an action to release the pool. |
952 |
> |
*/ |
953 |
> |
class PoolCleanerWithReleaser extends PoolCleaner { |
954 |
> |
private final Runnable releaser; |
955 |
> |
public PoolCleanerWithReleaser(ExecutorService pool, Runnable releaser) { |
956 |
> |
super(pool); |
957 |
> |
this.releaser = releaser; |
958 |
> |
} |
959 |
> |
public void close() { |
960 |
> |
try { |
961 |
> |
releaser.run(); |
962 |
> |
} finally { |
963 |
> |
super.close(); |
964 |
> |
} |
965 |
|
} |
966 |
|
} |
967 |
|
|
968 |
+ |
PoolCleaner cleaner(ExecutorService pool) { |
969 |
+ |
return new PoolCleaner(pool); |
970 |
+ |
} |
971 |
+ |
|
972 |
+ |
PoolCleaner cleaner(ExecutorService pool, Runnable releaser) { |
973 |
+ |
return new PoolCleanerWithReleaser(pool, releaser); |
974 |
+ |
} |
975 |
+ |
|
976 |
+ |
PoolCleaner cleaner(ExecutorService pool, CountDownLatch latch) { |
977 |
+ |
return new PoolCleanerWithReleaser(pool, releaser(latch)); |
978 |
+ |
} |
979 |
+ |
|
980 |
+ |
Runnable releaser(final CountDownLatch latch) { |
981 |
+ |
return new Runnable() { public void run() { |
982 |
+ |
do { latch.countDown(); } |
983 |
+ |
while (latch.getCount() > 0); |
984 |
+ |
}}; |
985 |
+ |
} |
986 |
+ |
|
987 |
+ |
PoolCleaner cleaner(ExecutorService pool, AtomicBoolean flag) { |
988 |
+ |
return new PoolCleanerWithReleaser(pool, releaser(flag)); |
989 |
+ |
} |
990 |
+ |
|
991 |
+ |
Runnable releaser(final AtomicBoolean flag) { |
992 |
+ |
return new Runnable() { public void run() { flag.set(true); }}; |
993 |
+ |
} |
994 |
+ |
|
995 |
|
/** |
996 |
|
* Waits out termination of a thread pool or fails doing so. |
997 |
|
*/ |
998 |
< |
public void joinPool(ExecutorService exec) { |
998 |
> |
void joinPool(ExecutorService pool) { |
999 |
|
try { |
1000 |
< |
exec.shutdown(); |
1001 |
< |
assertTrue("ExecutorService did not terminate in a timely manner", |
1002 |
< |
exec.awaitTermination(LONG_DELAY_MS, MILLISECONDS)); |
1000 |
> |
pool.shutdown(); |
1001 |
> |
if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS)) { |
1002 |
> |
try { |
1003 |
> |
threadFail("ExecutorService " + pool + |
1004 |
> |
" did not terminate in a timely manner"); |
1005 |
> |
} finally { |
1006 |
> |
// last resort, for the benefit of subsequent tests |
1007 |
> |
pool.shutdownNow(); |
1008 |
> |
pool.awaitTermination(MEDIUM_DELAY_MS, MILLISECONDS); |
1009 |
> |
} |
1010 |
> |
} |
1011 |
|
} catch (SecurityException ok) { |
1012 |
|
// Allowed in case test doesn't have privs |
1013 |
< |
} catch (InterruptedException ie) { |
1014 |
< |
fail("Unexpected InterruptedException"); |
1013 |
> |
} catch (InterruptedException fail) { |
1014 |
> |
threadFail("Unexpected InterruptedException"); |
1015 |
> |
} |
1016 |
> |
} |
1017 |
> |
|
1018 |
> |
/** |
1019 |
> |
* Like Runnable, but with the freedom to throw anything. |
1020 |
> |
* junit folks had the same idea: |
1021 |
> |
* http://junit.org/junit5/docs/snapshot/api/org/junit/gen5/api/Executable.html |
1022 |
> |
*/ |
1023 |
> |
interface Action { public void run() throws Throwable; } |
1024 |
> |
|
1025 |
> |
/** |
1026 |
> |
* Runs all the given actions in parallel, failing if any fail. |
1027 |
> |
* Useful for running multiple variants of tests that are |
1028 |
> |
* necessarily individually slow because they must block. |
1029 |
> |
*/ |
1030 |
> |
void testInParallel(Action ... actions) { |
1031 |
> |
ExecutorService pool = Executors.newCachedThreadPool(); |
1032 |
> |
try (PoolCleaner cleaner = cleaner(pool)) { |
1033 |
> |
ArrayList<Future<?>> futures = new ArrayList<>(actions.length); |
1034 |
> |
for (final Action action : actions) |
1035 |
> |
futures.add(pool.submit(new CheckedRunnable() { |
1036 |
> |
public void realRun() throws Throwable { action.run();}})); |
1037 |
> |
for (Future<?> future : futures) |
1038 |
> |
try { |
1039 |
> |
assertNull(future.get(LONG_DELAY_MS, MILLISECONDS)); |
1040 |
> |
} catch (ExecutionException ex) { |
1041 |
> |
threadUnexpectedException(ex.getCause()); |
1042 |
> |
} catch (Exception ex) { |
1043 |
> |
threadUnexpectedException(ex); |
1044 |
> |
} |
1045 |
> |
} |
1046 |
> |
} |
1047 |
> |
|
1048 |
> |
/** |
1049 |
> |
* A debugging tool to print stack traces of most threads, as jstack does. |
1050 |
> |
* Uninteresting threads are filtered out. |
1051 |
> |
*/ |
1052 |
> |
static void dumpTestThreads() { |
1053 |
> |
SecurityManager sm = System.getSecurityManager(); |
1054 |
> |
if (sm != null) { |
1055 |
> |
try { |
1056 |
> |
System.setSecurityManager(null); |
1057 |
> |
} catch (SecurityException giveUp) { |
1058 |
> |
return; |
1059 |
> |
} |
1060 |
|
} |
1061 |
+ |
|
1062 |
+ |
ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); |
1063 |
+ |
System.err.println("------ stacktrace dump start ------"); |
1064 |
+ |
for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) { |
1065 |
+ |
final String name = info.getThreadName(); |
1066 |
+ |
String lockName; |
1067 |
+ |
if ("Signal Dispatcher".equals(name)) |
1068 |
+ |
continue; |
1069 |
+ |
if ("Reference Handler".equals(name) |
1070 |
+ |
&& (lockName = info.getLockName()) != null |
1071 |
+ |
&& lockName.startsWith("java.lang.ref.Reference$Lock")) |
1072 |
+ |
continue; |
1073 |
+ |
if ("Finalizer".equals(name) |
1074 |
+ |
&& (lockName = info.getLockName()) != null |
1075 |
+ |
&& lockName.startsWith("java.lang.ref.ReferenceQueue$Lock")) |
1076 |
+ |
continue; |
1077 |
+ |
if ("checkForWedgedTest".equals(name)) |
1078 |
+ |
continue; |
1079 |
+ |
System.err.print(info); |
1080 |
+ |
} |
1081 |
+ |
System.err.println("------ stacktrace dump end ------"); |
1082 |
+ |
|
1083 |
+ |
if (sm != null) System.setSecurityManager(sm); |
1084 |
|
} |
1085 |
|
|
1086 |
+ |
/** |
1087 |
+ |
* Checks that thread eventually enters the expected blocked thread state. |
1088 |
+ |
*/ |
1089 |
+ |
void assertThreadBlocks(Thread thread, Thread.State expected) { |
1090 |
+ |
// always sleep at least 1 ms, with high probability avoiding |
1091 |
+ |
// transitory states |
1092 |
+ |
for (long retries = LONG_DELAY_MS * 3 / 4; retries-->0; ) { |
1093 |
+ |
try { delay(1); } |
1094 |
+ |
catch (InterruptedException fail) { |
1095 |
+ |
throw new AssertionError("Unexpected InterruptedException", fail); |
1096 |
+ |
} |
1097 |
+ |
Thread.State s = thread.getState(); |
1098 |
+ |
if (s == expected) |
1099 |
+ |
return; |
1100 |
+ |
else if (s == Thread.State.TERMINATED) |
1101 |
+ |
fail("Unexpected thread termination"); |
1102 |
+ |
} |
1103 |
+ |
fail("timed out waiting for thread to enter thread state " + expected); |
1104 |
+ |
} |
1105 |
+ |
|
1106 |
+ |
/** |
1107 |
+ |
* Checks that future.get times out, with the default timeout of |
1108 |
+ |
* {@code timeoutMillis()}. |
1109 |
+ |
*/ |
1110 |
+ |
void assertFutureTimesOut(Future future) { |
1111 |
+ |
assertFutureTimesOut(future, timeoutMillis()); |
1112 |
+ |
} |
1113 |
+ |
|
1114 |
+ |
/** |
1115 |
+ |
* Checks that future.get times out, with the given millisecond timeout. |
1116 |
+ |
*/ |
1117 |
+ |
void assertFutureTimesOut(Future future, long timeoutMillis) { |
1118 |
+ |
long startTime = System.nanoTime(); |
1119 |
+ |
try { |
1120 |
+ |
future.get(timeoutMillis, MILLISECONDS); |
1121 |
+ |
shouldThrow(); |
1122 |
+ |
} catch (TimeoutException success) { |
1123 |
+ |
} catch (Exception fail) { |
1124 |
+ |
threadUnexpectedException(fail); |
1125 |
+ |
} finally { future.cancel(true); } |
1126 |
+ |
assertTrue(millisElapsedSince(startTime) >= timeoutMillis); |
1127 |
+ |
} |
1128 |
|
|
1129 |
|
/** |
1130 |
|
* Fails with message "should throw exception". |
1141 |
|
} |
1142 |
|
|
1143 |
|
/** |
1144 |
+ |
* The maximum number of consecutive spurious wakeups we should |
1145 |
+ |
* tolerate (from APIs like LockSupport.park) before failing a test. |
1146 |
+ |
*/ |
1147 |
+ |
static final int MAX_SPURIOUS_WAKEUPS = 10; |
1148 |
+ |
|
1149 |
+ |
/** |
1150 |
|
* The number of elements to place in collections, arrays, etc. |
1151 |
|
*/ |
1152 |
|
public static final int SIZE = 20; |
1171 |
|
public static final Integer m6 = new Integer(-6); |
1172 |
|
public static final Integer m10 = new Integer(-10); |
1173 |
|
|
497 |
– |
|
1174 |
|
/** |
1175 |
|
* Runs Runnable r with a security policy that permits precisely |
1176 |
|
* the specified permissions. If there is no current security |
1182 |
|
SecurityManager sm = System.getSecurityManager(); |
1183 |
|
if (sm == null) { |
1184 |
|
r.run(); |
1185 |
+ |
} |
1186 |
+ |
runWithSecurityManagerWithPermissions(r, permissions); |
1187 |
+ |
} |
1188 |
+ |
|
1189 |
+ |
/** |
1190 |
+ |
* Runs Runnable r with a security policy that permits precisely |
1191 |
+ |
* the specified permissions. If there is no current security |
1192 |
+ |
* manager, a temporary one is set for the duration of the |
1193 |
+ |
* Runnable. We require that any security manager permit |
1194 |
+ |
* getPolicy/setPolicy. |
1195 |
+ |
*/ |
1196 |
+ |
public void runWithSecurityManagerWithPermissions(Runnable r, |
1197 |
+ |
Permission... permissions) { |
1198 |
+ |
SecurityManager sm = System.getSecurityManager(); |
1199 |
+ |
if (sm == null) { |
1200 |
|
Policy savedPolicy = Policy.getPolicy(); |
1201 |
|
try { |
1202 |
|
Policy.setPolicy(permissivePolicy()); |
1203 |
|
System.setSecurityManager(new SecurityManager()); |
1204 |
< |
runWithPermissions(r, permissions); |
1204 |
> |
runWithSecurityManagerWithPermissions(r, permissions); |
1205 |
|
} finally { |
1206 |
|
System.setSecurityManager(null); |
1207 |
|
Policy.setPolicy(savedPolicy); |
1249 |
|
return perms.implies(p); |
1250 |
|
} |
1251 |
|
public void refresh() {} |
1252 |
+ |
public String toString() { |
1253 |
+ |
List<Permission> ps = new ArrayList<>(); |
1254 |
+ |
for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();) |
1255 |
+ |
ps.add(e.nextElement()); |
1256 |
+ |
return "AdjustablePolicy with permissions " + ps; |
1257 |
+ |
} |
1258 |
|
} |
1259 |
|
|
1260 |
|
/** |
1278 |
|
|
1279 |
|
/** |
1280 |
|
* Sleeps until the given time has elapsed. |
1281 |
< |
* Throws AssertionFailedError if interrupted. |
1281 |
> |
* Throws AssertionError if interrupted. |
1282 |
|
*/ |
1283 |
< |
void sleep(long millis) { |
1283 |
> |
static void sleep(long millis) { |
1284 |
|
try { |
1285 |
< |
Thread.sleep(millis); |
1286 |
< |
} catch (InterruptedException ie) { |
1287 |
< |
AssertionFailedError afe = |
591 |
< |
new AssertionFailedError("Unexpected InterruptedException"); |
592 |
< |
afe.initCause(ie); |
593 |
< |
throw afe; |
1285 |
> |
delay(millis); |
1286 |
> |
} catch (InterruptedException fail) { |
1287 |
> |
throw new AssertionError("Unexpected InterruptedException", fail); |
1288 |
|
} |
1289 |
|
} |
1290 |
|
|
1291 |
|
/** |
1292 |
< |
* Sleeps until the timeout has elapsed, or interrupted. |
599 |
< |
* Does <em>NOT</em> throw InterruptedException. |
600 |
< |
*/ |
601 |
< |
void sleepTillInterrupted(long timeoutMillis) { |
602 |
< |
try { |
603 |
< |
Thread.sleep(timeoutMillis); |
604 |
< |
} catch (InterruptedException wakeup) {} |
605 |
< |
} |
606 |
< |
|
607 |
< |
/** |
608 |
< |
* Waits up to the specified number of milliseconds for the given |
1292 |
> |
* Spin-waits up to the specified number of milliseconds for the given |
1293 |
|
* thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING. |
1294 |
|
*/ |
1295 |
|
void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) { |
1296 |
< |
long timeoutNanos = timeoutMillis * 1000L * 1000L; |
613 |
< |
long t0 = System.nanoTime(); |
1296 |
> |
long startTime = 0L; |
1297 |
|
for (;;) { |
1298 |
|
Thread.State s = thread.getState(); |
1299 |
|
if (s == Thread.State.BLOCKED || |
1300 |
|
s == Thread.State.WAITING || |
1301 |
< |
s == Thread.State.TIMED_WAITING || |
619 |
< |
System.nanoTime() - t0 > timeoutNanos) |
1301 |
> |
s == Thread.State.TIMED_WAITING) |
1302 |
|
return; |
1303 |
+ |
else if (s == Thread.State.TERMINATED) |
1304 |
+ |
fail("Unexpected thread termination"); |
1305 |
+ |
else if (startTime == 0L) |
1306 |
+ |
startTime = System.nanoTime(); |
1307 |
+ |
else if (millisElapsedSince(startTime) > timeoutMillis) { |
1308 |
+ |
threadAssertTrue(thread.isAlive()); |
1309 |
+ |
fail("timed out waiting for thread to enter wait state"); |
1310 |
+ |
} |
1311 |
|
Thread.yield(); |
1312 |
|
} |
1313 |
|
} |
1314 |
|
|
1315 |
|
/** |
1316 |
+ |
* Spin-waits up to the specified number of milliseconds for the given |
1317 |
+ |
* thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING, |
1318 |
+ |
* and additionally satisfy the given condition. |
1319 |
+ |
*/ |
1320 |
+ |
void waitForThreadToEnterWaitState( |
1321 |
+ |
Thread thread, long timeoutMillis, Callable<Boolean> waitingForGodot) { |
1322 |
+ |
long startTime = 0L; |
1323 |
+ |
for (;;) { |
1324 |
+ |
Thread.State s = thread.getState(); |
1325 |
+ |
if (s == Thread.State.BLOCKED || |
1326 |
+ |
s == Thread.State.WAITING || |
1327 |
+ |
s == Thread.State.TIMED_WAITING) { |
1328 |
+ |
try { |
1329 |
+ |
if (waitingForGodot.call()) |
1330 |
+ |
return; |
1331 |
+ |
} catch (Throwable fail) { threadUnexpectedException(fail); } |
1332 |
+ |
} |
1333 |
+ |
else if (s == Thread.State.TERMINATED) |
1334 |
+ |
fail("Unexpected thread termination"); |
1335 |
+ |
else if (startTime == 0L) |
1336 |
+ |
startTime = System.nanoTime(); |
1337 |
+ |
else if (millisElapsedSince(startTime) > timeoutMillis) { |
1338 |
+ |
threadAssertTrue(thread.isAlive()); |
1339 |
+ |
fail("timed out waiting for thread to enter wait state"); |
1340 |
+ |
} |
1341 |
+ |
Thread.yield(); |
1342 |
+ |
} |
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 |
+ |
*/ |
1349 |
+ |
void waitForThreadToEnterWaitState(Thread thread) { |
1350 |
+ |
waitForThreadToEnterWaitState(thread, LONG_DELAY_MS); |
1351 |
+ |
} |
1352 |
+ |
|
1353 |
+ |
/** |
1354 |
+ |
* Spin-waits up to LONG_DELAY_MS milliseconds for the given thread to |
1355 |
+ |
* enter a wait state: BLOCKED, WAITING, or TIMED_WAITING, |
1356 |
+ |
* and additionally satisfy the given condition. |
1357 |
+ |
*/ |
1358 |
+ |
void waitForThreadToEnterWaitState( |
1359 |
+ |
Thread thread, Callable<Boolean> waitingForGodot) { |
1360 |
+ |
waitForThreadToEnterWaitState(thread, LONG_DELAY_MS, waitingForGodot); |
1361 |
+ |
} |
1362 |
+ |
|
1363 |
+ |
/** |
1364 |
+ |
* Returns the number of milliseconds since time given by |
1365 |
+ |
* startNanoTime, which must have been previously returned from a |
1366 |
+ |
* call to {@link System#nanoTime()}. |
1367 |
+ |
*/ |
1368 |
+ |
static long millisElapsedSince(long startNanoTime) { |
1369 |
+ |
return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime); |
1370 |
+ |
} |
1371 |
+ |
|
1372 |
+ |
// void assertTerminatesPromptly(long timeoutMillis, Runnable r) { |
1373 |
+ |
// long startTime = System.nanoTime(); |
1374 |
+ |
// try { |
1375 |
+ |
// r.run(); |
1376 |
+ |
// } catch (Throwable fail) { threadUnexpectedException(fail); } |
1377 |
+ |
// if (millisElapsedSince(startTime) > timeoutMillis/2) |
1378 |
+ |
// throw new AssertionError("did not return promptly"); |
1379 |
+ |
// } |
1380 |
+ |
|
1381 |
+ |
// void assertTerminatesPromptly(Runnable r) { |
1382 |
+ |
// assertTerminatesPromptly(LONG_DELAY_MS/2, r); |
1383 |
+ |
// } |
1384 |
+ |
|
1385 |
+ |
/** |
1386 |
+ |
* Checks that timed f.get() returns the expected value, and does not |
1387 |
+ |
* wait for the timeout to elapse before returning. |
1388 |
+ |
*/ |
1389 |
+ |
<T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) { |
1390 |
+ |
long startTime = System.nanoTime(); |
1391 |
+ |
try { |
1392 |
+ |
assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS)); |
1393 |
+ |
} catch (Throwable fail) { threadUnexpectedException(fail); } |
1394 |
+ |
if (millisElapsedSince(startTime) > timeoutMillis/2) |
1395 |
+ |
throw new AssertionError("timed get did not return promptly"); |
1396 |
+ |
} |
1397 |
+ |
|
1398 |
+ |
<T> void checkTimedGet(Future<T> f, T expectedValue) { |
1399 |
+ |
checkTimedGet(f, expectedValue, LONG_DELAY_MS); |
1400 |
+ |
} |
1401 |
+ |
|
1402 |
+ |
/** |
1403 |
|
* Returns a new started daemon Thread running the given runnable. |
1404 |
|
*/ |
1405 |
|
Thread newStartedThread(Runnable runnable) { |
1417 |
|
void awaitTermination(Thread t, long timeoutMillis) { |
1418 |
|
try { |
1419 |
|
t.join(timeoutMillis); |
1420 |
< |
} catch (InterruptedException ie) { |
1421 |
< |
threadUnexpectedException(ie); |
1420 |
> |
} catch (InterruptedException fail) { |
1421 |
> |
threadUnexpectedException(fail); |
1422 |
|
} finally { |
1423 |
< |
if (t.isAlive()) { |
1423 |
> |
if (t.getState() != Thread.State.TERMINATED) { |
1424 |
|
t.interrupt(); |
1425 |
< |
fail("Test timed out"); |
1425 |
> |
threadFail("timed out waiting for thread to terminate"); |
1426 |
|
} |
1427 |
|
} |
1428 |
|
} |
1429 |
|
|
1430 |
+ |
/** |
1431 |
+ |
* Waits for LONG_DELAY_MS milliseconds for the thread to |
1432 |
+ |
* terminate (using {@link Thread#join(long)}), else interrupts |
1433 |
+ |
* the thread (in the hope that it may terminate later) and fails. |
1434 |
+ |
*/ |
1435 |
+ |
void awaitTermination(Thread t) { |
1436 |
+ |
awaitTermination(t, LONG_DELAY_MS); |
1437 |
+ |
} |
1438 |
+ |
|
1439 |
|
// Some convenient Runnable classes |
1440 |
|
|
1441 |
|
public abstract class CheckedRunnable implements Runnable { |
1444 |
|
public final void run() { |
1445 |
|
try { |
1446 |
|
realRun(); |
1447 |
< |
} catch (Throwable t) { |
1448 |
< |
threadUnexpectedException(t); |
663 |
< |
} |
664 |
< |
} |
665 |
< |
} |
666 |
< |
|
667 |
< |
public abstract class RunnableShouldThrow implements Runnable { |
668 |
< |
protected abstract void realRun() throws Throwable; |
669 |
< |
|
670 |
< |
final Class<?> exceptionClass; |
671 |
< |
|
672 |
< |
<T extends Throwable> RunnableShouldThrow(Class<T> exceptionClass) { |
673 |
< |
this.exceptionClass = exceptionClass; |
674 |
< |
} |
675 |
< |
|
676 |
< |
public final void run() { |
677 |
< |
try { |
678 |
< |
realRun(); |
679 |
< |
threadShouldThrow(exceptionClass.getSimpleName()); |
680 |
< |
} catch (Throwable t) { |
681 |
< |
if (! exceptionClass.isInstance(t)) |
682 |
< |
threadUnexpectedException(t); |
1447 |
> |
} catch (Throwable fail) { |
1448 |
> |
threadUnexpectedException(fail); |
1449 |
|
} |
1450 |
|
} |
1451 |
|
} |
1478 |
|
realRun(); |
1479 |
|
threadShouldThrow("InterruptedException"); |
1480 |
|
} catch (InterruptedException success) { |
1481 |
< |
} catch (Throwable t) { |
1482 |
< |
threadUnexpectedException(t); |
1481 |
> |
threadAssertFalse(Thread.interrupted()); |
1482 |
> |
} catch (Throwable fail) { |
1483 |
> |
threadUnexpectedException(fail); |
1484 |
|
} |
1485 |
|
} |
1486 |
|
} |
1491 |
|
public final T call() { |
1492 |
|
try { |
1493 |
|
return realCall(); |
1494 |
< |
} catch (Throwable t) { |
1495 |
< |
threadUnexpectedException(t); |
1494 |
> |
} catch (Throwable fail) { |
1495 |
> |
threadUnexpectedException(fail); |
1496 |
|
return null; |
1497 |
|
} |
1498 |
|
} |
1508 |
|
threadShouldThrow("InterruptedException"); |
1509 |
|
return result; |
1510 |
|
} catch (InterruptedException success) { |
1511 |
< |
} catch (Throwable t) { |
1512 |
< |
threadUnexpectedException(t); |
1511 |
> |
threadAssertFalse(Thread.interrupted()); |
1512 |
> |
} catch (Throwable fail) { |
1513 |
> |
threadUnexpectedException(fail); |
1514 |
|
} |
1515 |
|
return null; |
1516 |
|
} |
1527 |
|
public static final String TEST_STRING = "a test string"; |
1528 |
|
|
1529 |
|
public static class StringTask implements Callable<String> { |
1530 |
< |
public String call() { return TEST_STRING; } |
1530 |
> |
final String value; |
1531 |
> |
public StringTask() { this(TEST_STRING); } |
1532 |
> |
public StringTask(String value) { this.value = value; } |
1533 |
> |
public String call() { return value; } |
1534 |
|
} |
1535 |
|
|
1536 |
|
public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) { |
1543 |
|
}}; |
1544 |
|
} |
1545 |
|
|
1546 |
< |
public static class NPETask implements Callable<String> { |
1547 |
< |
public String call() { throw new NullPointerException(); } |
1546 |
> |
public Runnable countDowner(final CountDownLatch latch) { |
1547 |
> |
return new CheckedRunnable() { |
1548 |
> |
public void realRun() throws InterruptedException { |
1549 |
> |
latch.countDown(); |
1550 |
> |
}}; |
1551 |
|
} |
1552 |
|
|
1553 |
< |
public static class CallableOne implements Callable<Integer> { |
1554 |
< |
public Integer call() { return one; } |
1553 |
> |
class LatchAwaiter extends CheckedRunnable { |
1554 |
> |
static final int NEW = 0; |
1555 |
> |
static final int RUNNING = 1; |
1556 |
> |
static final int DONE = 2; |
1557 |
> |
final CountDownLatch latch; |
1558 |
> |
int state = NEW; |
1559 |
> |
LatchAwaiter(CountDownLatch latch) { this.latch = latch; } |
1560 |
> |
public void realRun() throws InterruptedException { |
1561 |
> |
state = 1; |
1562 |
> |
await(latch); |
1563 |
> |
state = 2; |
1564 |
> |
} |
1565 |
|
} |
1566 |
|
|
1567 |
< |
public class ShortRunnable extends CheckedRunnable { |
1568 |
< |
protected void realRun() throws Throwable { |
785 |
< |
Thread.sleep(SHORT_DELAY_MS); |
786 |
< |
} |
1567 |
> |
public LatchAwaiter awaiter(CountDownLatch latch) { |
1568 |
> |
return new LatchAwaiter(latch); |
1569 |
|
} |
1570 |
|
|
1571 |
< |
public class ShortInterruptedRunnable extends CheckedInterruptedRunnable { |
1572 |
< |
protected void realRun() throws InterruptedException { |
1573 |
< |
Thread.sleep(SHORT_DELAY_MS); |
1571 |
> |
public void await(CountDownLatch latch, long timeoutMillis) { |
1572 |
> |
try { |
1573 |
> |
if (!latch.await(timeoutMillis, MILLISECONDS)) |
1574 |
> |
fail("timed out waiting for CountDownLatch for " |
1575 |
> |
+ (timeoutMillis/1000) + " sec"); |
1576 |
> |
} catch (Throwable fail) { |
1577 |
> |
threadUnexpectedException(fail); |
1578 |
|
} |
1579 |
|
} |
1580 |
|
|
1581 |
< |
public class SmallRunnable extends CheckedRunnable { |
1582 |
< |
protected void realRun() throws Throwable { |
797 |
< |
Thread.sleep(SMALL_DELAY_MS); |
798 |
< |
} |
1581 |
> |
public void await(CountDownLatch latch) { |
1582 |
> |
await(latch, LONG_DELAY_MS); |
1583 |
|
} |
1584 |
|
|
1585 |
< |
public class SmallPossiblyInterruptedRunnable extends CheckedRunnable { |
1586 |
< |
protected void realRun() { |
1587 |
< |
try { |
1588 |
< |
Thread.sleep(SMALL_DELAY_MS); |
1589 |
< |
} catch (InterruptedException ok) {} |
1585 |
> |
public void await(Semaphore semaphore) { |
1586 |
> |
try { |
1587 |
> |
if (!semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS)) |
1588 |
> |
fail("timed out waiting for Semaphore for " |
1589 |
> |
+ (LONG_DELAY_MS/1000) + " sec"); |
1590 |
> |
} catch (Throwable fail) { |
1591 |
> |
threadUnexpectedException(fail); |
1592 |
|
} |
1593 |
|
} |
1594 |
|
|
1595 |
< |
public class SmallCallable extends CheckedCallable { |
1596 |
< |
protected Object realCall() throws InterruptedException { |
1597 |
< |
Thread.sleep(SMALL_DELAY_MS); |
1598 |
< |
return Boolean.TRUE; |
1595 |
> |
public void await(CyclicBarrier barrier) { |
1596 |
> |
try { |
1597 |
> |
barrier.await(LONG_DELAY_MS, MILLISECONDS); |
1598 |
> |
} catch (Throwable fail) { |
1599 |
> |
threadUnexpectedException(fail); |
1600 |
|
} |
1601 |
|
} |
1602 |
|
|
1603 |
< |
public class MediumRunnable extends CheckedRunnable { |
1604 |
< |
protected void realRun() throws Throwable { |
1605 |
< |
Thread.sleep(MEDIUM_DELAY_MS); |
1606 |
< |
} |
1603 |
> |
// /** |
1604 |
> |
// * Spin-waits up to LONG_DELAY_MS until flag becomes true. |
1605 |
> |
// */ |
1606 |
> |
// public void await(AtomicBoolean flag) { |
1607 |
> |
// await(flag, LONG_DELAY_MS); |
1608 |
> |
// } |
1609 |
> |
|
1610 |
> |
// /** |
1611 |
> |
// * Spin-waits up to the specified timeout until flag becomes true. |
1612 |
> |
// */ |
1613 |
> |
// public void await(AtomicBoolean flag, long timeoutMillis) { |
1614 |
> |
// long startTime = System.nanoTime(); |
1615 |
> |
// while (!flag.get()) { |
1616 |
> |
// if (millisElapsedSince(startTime) > timeoutMillis) |
1617 |
> |
// throw new AssertionError("timed out"); |
1618 |
> |
// Thread.yield(); |
1619 |
> |
// } |
1620 |
> |
// } |
1621 |
> |
|
1622 |
> |
public static class NPETask implements Callable<String> { |
1623 |
> |
public String call() { throw new NullPointerException(); } |
1624 |
|
} |
1625 |
|
|
1626 |
< |
public class MediumInterruptedRunnable extends CheckedInterruptedRunnable { |
1627 |
< |
protected void realRun() throws InterruptedException { |
1628 |
< |
Thread.sleep(MEDIUM_DELAY_MS); |
1626 |
> |
public class SmallPossiblyInterruptedRunnable extends CheckedRunnable { |
1627 |
> |
protected void realRun() { |
1628 |
> |
try { |
1629 |
> |
delay(SMALL_DELAY_MS); |
1630 |
> |
} catch (InterruptedException ok) {} |
1631 |
|
} |
1632 |
|
} |
1633 |
|
|
1635 |
|
return new CheckedRunnable() { |
1636 |
|
protected void realRun() { |
1637 |
|
try { |
1638 |
< |
Thread.sleep(timeoutMillis); |
1638 |
> |
delay(timeoutMillis); |
1639 |
|
} catch (InterruptedException ok) {} |
1640 |
|
}}; |
1641 |
|
} |
1642 |
|
|
837 |
– |
public class MediumPossiblyInterruptedRunnable extends CheckedRunnable { |
838 |
– |
protected void realRun() { |
839 |
– |
try { |
840 |
– |
Thread.sleep(MEDIUM_DELAY_MS); |
841 |
– |
} catch (InterruptedException ok) {} |
842 |
– |
} |
843 |
– |
} |
844 |
– |
|
845 |
– |
public class LongPossiblyInterruptedRunnable extends CheckedRunnable { |
846 |
– |
protected void realRun() { |
847 |
– |
try { |
848 |
– |
Thread.sleep(LONG_DELAY_MS); |
849 |
– |
} catch (InterruptedException ok) {} |
850 |
– |
} |
851 |
– |
} |
852 |
– |
|
1643 |
|
/** |
1644 |
|
* For use as ThreadFactory in constructors |
1645 |
|
*/ |
1653 |
|
boolean isDone(); |
1654 |
|
} |
1655 |
|
|
866 |
– |
public static TrackedRunnable trackedRunnable(final long timeoutMillis) { |
867 |
– |
return new TrackedRunnable() { |
868 |
– |
private volatile boolean done = false; |
869 |
– |
public boolean isDone() { return done; } |
870 |
– |
public void run() { |
871 |
– |
try { |
872 |
– |
Thread.sleep(timeoutMillis); |
873 |
– |
done = true; |
874 |
– |
} catch (InterruptedException ok) {} |
875 |
– |
} |
876 |
– |
}; |
877 |
– |
} |
878 |
– |
|
879 |
– |
public static class TrackedShortRunnable implements Runnable { |
880 |
– |
public volatile boolean done = false; |
881 |
– |
public void run() { |
882 |
– |
try { |
883 |
– |
Thread.sleep(SHORT_DELAY_MS); |
884 |
– |
done = true; |
885 |
– |
} catch (InterruptedException ok) {} |
886 |
– |
} |
887 |
– |
} |
888 |
– |
|
889 |
– |
public static class TrackedSmallRunnable implements Runnable { |
890 |
– |
public volatile boolean done = false; |
891 |
– |
public void run() { |
892 |
– |
try { |
893 |
– |
Thread.sleep(SMALL_DELAY_MS); |
894 |
– |
done = true; |
895 |
– |
} catch (InterruptedException ok) {} |
896 |
– |
} |
897 |
– |
} |
898 |
– |
|
899 |
– |
public static class TrackedMediumRunnable implements Runnable { |
900 |
– |
public volatile boolean done = false; |
901 |
– |
public void run() { |
902 |
– |
try { |
903 |
– |
Thread.sleep(MEDIUM_DELAY_MS); |
904 |
– |
done = true; |
905 |
– |
} catch (InterruptedException ok) {} |
906 |
– |
} |
907 |
– |
} |
908 |
– |
|
909 |
– |
public static class TrackedLongRunnable implements Runnable { |
910 |
– |
public volatile boolean done = false; |
911 |
– |
public void run() { |
912 |
– |
try { |
913 |
– |
Thread.sleep(LONG_DELAY_MS); |
914 |
– |
done = true; |
915 |
– |
} catch (InterruptedException ok) {} |
916 |
– |
} |
917 |
– |
} |
918 |
– |
|
1656 |
|
public static class TrackedNoOpRunnable implements Runnable { |
1657 |
|
public volatile boolean done = false; |
1658 |
|
public void run() { |
1660 |
|
} |
1661 |
|
} |
1662 |
|
|
926 |
– |
public static class TrackedCallable implements Callable { |
927 |
– |
public volatile boolean done = false; |
928 |
– |
public Object call() { |
929 |
– |
try { |
930 |
– |
Thread.sleep(SMALL_DELAY_MS); |
931 |
– |
done = true; |
932 |
– |
} catch (InterruptedException ok) {} |
933 |
– |
return Boolean.TRUE; |
934 |
– |
} |
935 |
– |
} |
936 |
– |
|
1663 |
|
/** |
1664 |
|
* Analog of CheckedRunnable for RecursiveAction |
1665 |
|
*/ |
1666 |
|
public abstract class CheckedRecursiveAction extends RecursiveAction { |
1667 |
|
protected abstract void realCompute() throws Throwable; |
1668 |
|
|
1669 |
< |
public final void compute() { |
1669 |
> |
@Override protected final void compute() { |
1670 |
|
try { |
1671 |
|
realCompute(); |
1672 |
< |
} catch (Throwable t) { |
1673 |
< |
threadUnexpectedException(t); |
1672 |
> |
} catch (Throwable fail) { |
1673 |
> |
threadUnexpectedException(fail); |
1674 |
|
} |
1675 |
|
} |
1676 |
|
} |
1681 |
|
public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> { |
1682 |
|
protected abstract T realCompute() throws Throwable; |
1683 |
|
|
1684 |
< |
public final T compute() { |
1684 |
> |
@Override protected final T compute() { |
1685 |
|
try { |
1686 |
|
return realCompute(); |
1687 |
< |
} catch (Throwable t) { |
1688 |
< |
threadUnexpectedException(t); |
1687 |
> |
} catch (Throwable fail) { |
1688 |
> |
threadUnexpectedException(fail); |
1689 |
|
return null; |
1690 |
|
} |
1691 |
|
} |
1700 |
|
} |
1701 |
|
|
1702 |
|
/** |
1703 |
< |
* A CyclicBarrier that fails with AssertionFailedErrors instead |
1704 |
< |
* of throwing checked exceptions. |
1703 |
> |
* A CyclicBarrier that uses timed await and fails with |
1704 |
> |
* AssertionErrors instead of throwing checked exceptions. |
1705 |
|
*/ |
1706 |
< |
public class CheckedBarrier extends CyclicBarrier { |
1706 |
> |
public static class CheckedBarrier extends CyclicBarrier { |
1707 |
|
public CheckedBarrier(int parties) { super(parties); } |
1708 |
|
|
1709 |
|
public int await() { |
1710 |
|
try { |
1711 |
< |
return super.await(); |
1712 |
< |
} catch (Exception e) { |
1713 |
< |
AssertionFailedError afe = |
1714 |
< |
new AssertionFailedError("Unexpected exception: " + e); |
1715 |
< |
afe.initCause(e); |
990 |
< |
throw afe; |
1711 |
> |
return super.await(2 * LONG_DELAY_MS, MILLISECONDS); |
1712 |
> |
} catch (TimeoutException timedOut) { |
1713 |
> |
throw new AssertionError("timed out"); |
1714 |
> |
} catch (Exception fail) { |
1715 |
> |
throw new AssertionError("Unexpected exception: " + fail, fail); |
1716 |
|
} |
1717 |
|
} |
1718 |
|
} |
1719 |
|
|
1720 |
+ |
void checkEmpty(BlockingQueue q) { |
1721 |
+ |
try { |
1722 |
+ |
assertTrue(q.isEmpty()); |
1723 |
+ |
assertEquals(0, q.size()); |
1724 |
+ |
assertNull(q.peek()); |
1725 |
+ |
assertNull(q.poll()); |
1726 |
+ |
assertNull(q.poll(randomExpiredTimeout(), randomTimeUnit())); |
1727 |
+ |
assertEquals(q.toString(), "[]"); |
1728 |
+ |
assertTrue(Arrays.equals(q.toArray(), new Object[0])); |
1729 |
+ |
assertFalse(q.iterator().hasNext()); |
1730 |
+ |
try { |
1731 |
+ |
q.element(); |
1732 |
+ |
shouldThrow(); |
1733 |
+ |
} catch (NoSuchElementException success) {} |
1734 |
+ |
try { |
1735 |
+ |
q.iterator().next(); |
1736 |
+ |
shouldThrow(); |
1737 |
+ |
} catch (NoSuchElementException success) {} |
1738 |
+ |
try { |
1739 |
+ |
q.remove(); |
1740 |
+ |
shouldThrow(); |
1741 |
+ |
} catch (NoSuchElementException success) {} |
1742 |
+ |
} catch (InterruptedException fail) { threadUnexpectedException(fail); } |
1743 |
+ |
} |
1744 |
+ |
|
1745 |
+ |
void assertSerialEquals(Object x, Object y) { |
1746 |
+ |
assertTrue(Arrays.equals(serialBytes(x), serialBytes(y))); |
1747 |
+ |
} |
1748 |
+ |
|
1749 |
+ |
void assertNotSerialEquals(Object x, Object y) { |
1750 |
+ |
assertFalse(Arrays.equals(serialBytes(x), serialBytes(y))); |
1751 |
+ |
} |
1752 |
+ |
|
1753 |
+ |
byte[] serialBytes(Object o) { |
1754 |
+ |
try { |
1755 |
+ |
ByteArrayOutputStream bos = new ByteArrayOutputStream(); |
1756 |
+ |
ObjectOutputStream oos = new ObjectOutputStream(bos); |
1757 |
+ |
oos.writeObject(o); |
1758 |
+ |
oos.flush(); |
1759 |
+ |
oos.close(); |
1760 |
+ |
return bos.toByteArray(); |
1761 |
+ |
} catch (Throwable fail) { |
1762 |
+ |
threadUnexpectedException(fail); |
1763 |
+ |
return new byte[0]; |
1764 |
+ |
} |
1765 |
+ |
} |
1766 |
+ |
|
1767 |
+ |
void assertImmutable(final Object o) { |
1768 |
+ |
if (o instanceof Collection) { |
1769 |
+ |
assertThrows( |
1770 |
+ |
UnsupportedOperationException.class, |
1771 |
+ |
new Runnable() { public void run() { |
1772 |
+ |
((Collection) o).add(null);}}); |
1773 |
+ |
} |
1774 |
+ |
} |
1775 |
+ |
|
1776 |
+ |
@SuppressWarnings("unchecked") |
1777 |
+ |
<T> T serialClone(T o) { |
1778 |
+ |
try { |
1779 |
+ |
ObjectInputStream ois = new ObjectInputStream |
1780 |
+ |
(new ByteArrayInputStream(serialBytes(o))); |
1781 |
+ |
T clone = (T) ois.readObject(); |
1782 |
+ |
if (o == clone) assertImmutable(o); |
1783 |
+ |
assertSame(o.getClass(), clone.getClass()); |
1784 |
+ |
return clone; |
1785 |
+ |
} catch (Throwable fail) { |
1786 |
+ |
threadUnexpectedException(fail); |
1787 |
+ |
return null; |
1788 |
+ |
} |
1789 |
+ |
} |
1790 |
+ |
|
1791 |
+ |
/** |
1792 |
+ |
* A version of serialClone that leaves error handling (for |
1793 |
+ |
* e.g. NotSerializableException) up to the caller. |
1794 |
+ |
*/ |
1795 |
+ |
@SuppressWarnings("unchecked") |
1796 |
+ |
<T> T serialClonePossiblyFailing(T o) |
1797 |
+ |
throws ReflectiveOperationException, java.io.IOException { |
1798 |
+ |
ByteArrayOutputStream bos = new ByteArrayOutputStream(); |
1799 |
+ |
ObjectOutputStream oos = new ObjectOutputStream(bos); |
1800 |
+ |
oos.writeObject(o); |
1801 |
+ |
oos.flush(); |
1802 |
+ |
oos.close(); |
1803 |
+ |
ObjectInputStream ois = new ObjectInputStream |
1804 |
+ |
(new ByteArrayInputStream(bos.toByteArray())); |
1805 |
+ |
T clone = (T) ois.readObject(); |
1806 |
+ |
if (o == clone) assertImmutable(o); |
1807 |
+ |
assertSame(o.getClass(), clone.getClass()); |
1808 |
+ |
return clone; |
1809 |
+ |
} |
1810 |
+ |
|
1811 |
+ |
/** |
1812 |
+ |
* If o implements Cloneable and has a public clone method, |
1813 |
+ |
* returns a clone of o, else null. |
1814 |
+ |
*/ |
1815 |
+ |
@SuppressWarnings("unchecked") |
1816 |
+ |
<T> T cloneableClone(T o) { |
1817 |
+ |
if (!(o instanceof Cloneable)) return null; |
1818 |
+ |
final T clone; |
1819 |
+ |
try { |
1820 |
+ |
clone = (T) o.getClass().getMethod("clone").invoke(o); |
1821 |
+ |
} catch (NoSuchMethodException ok) { |
1822 |
+ |
return null; |
1823 |
+ |
} catch (ReflectiveOperationException unexpected) { |
1824 |
+ |
throw new Error(unexpected); |
1825 |
+ |
} |
1826 |
+ |
assertNotSame(o, clone); // not 100% guaranteed by spec |
1827 |
+ |
assertSame(o.getClass(), clone.getClass()); |
1828 |
+ |
return clone; |
1829 |
+ |
} |
1830 |
+ |
|
1831 |
+ |
public void assertThrows(Class<? extends Throwable> expectedExceptionClass, |
1832 |
+ |
Runnable... throwingActions) { |
1833 |
+ |
for (Runnable throwingAction : throwingActions) { |
1834 |
+ |
boolean threw = false; |
1835 |
+ |
try { throwingAction.run(); } |
1836 |
+ |
catch (Throwable t) { |
1837 |
+ |
threw = true; |
1838 |
+ |
if (!expectedExceptionClass.isInstance(t)) |
1839 |
+ |
throw new AssertionError( |
1840 |
+ |
"Expected " + expectedExceptionClass.getName() + |
1841 |
+ |
", got " + t.getClass().getName(), |
1842 |
+ |
t); |
1843 |
+ |
} |
1844 |
+ |
if (!threw) |
1845 |
+ |
shouldThrow(expectedExceptionClass.getName()); |
1846 |
+ |
} |
1847 |
+ |
} |
1848 |
+ |
|
1849 |
+ |
public void assertIteratorExhausted(Iterator<?> it) { |
1850 |
+ |
try { |
1851 |
+ |
it.next(); |
1852 |
+ |
shouldThrow(); |
1853 |
+ |
} catch (NoSuchElementException success) {} |
1854 |
+ |
assertFalse(it.hasNext()); |
1855 |
+ |
} |
1856 |
+ |
|
1857 |
+ |
public <T> Callable<T> callableThrowing(final Exception ex) { |
1858 |
+ |
return new Callable<T>() { public T call() throws Exception { throw ex; }}; |
1859 |
+ |
} |
1860 |
+ |
|
1861 |
+ |
public Runnable runnableThrowing(final RuntimeException ex) { |
1862 |
+ |
return new Runnable() { public void run() { throw ex; }}; |
1863 |
+ |
} |
1864 |
+ |
|
1865 |
+ |
/** A reusable thread pool to be shared by tests. */ |
1866 |
+ |
static final ExecutorService cachedThreadPool = |
1867 |
+ |
new ThreadPoolExecutor(0, Integer.MAX_VALUE, |
1868 |
+ |
1000L, MILLISECONDS, |
1869 |
+ |
new SynchronousQueue<Runnable>()); |
1870 |
+ |
|
1871 |
+ |
static <T> void shuffle(T[] array) { |
1872 |
+ |
Collections.shuffle(Arrays.asList(array), ThreadLocalRandom.current()); |
1873 |
+ |
} |
1874 |
+ |
|
1875 |
+ |
/** |
1876 |
+ |
* Returns the same String as would be returned by {@link |
1877 |
+ |
* Object#toString}, whether or not the given object's class |
1878 |
+ |
* overrides toString(). |
1879 |
+ |
* |
1880 |
+ |
* @see System#identityHashCode |
1881 |
+ |
*/ |
1882 |
+ |
static String identityString(Object x) { |
1883 |
+ |
return x.getClass().getName() |
1884 |
+ |
+ "@" + Integer.toHexString(System.identityHashCode(x)); |
1885 |
+ |
} |
1886 |
+ |
|
1887 |
+ |
// --- Shared assertions for Executor tests --- |
1888 |
+ |
|
1889 |
+ |
/** |
1890 |
+ |
* Returns maximum number of tasks that can be submitted to given |
1891 |
+ |
* pool (with bounded queue) before saturation (when submission |
1892 |
+ |
* throws RejectedExecutionException). |
1893 |
+ |
*/ |
1894 |
+ |
static final int saturatedSize(ThreadPoolExecutor pool) { |
1895 |
+ |
BlockingQueue<Runnable> q = pool.getQueue(); |
1896 |
+ |
return pool.getMaximumPoolSize() + q.size() + q.remainingCapacity(); |
1897 |
+ |
} |
1898 |
+ |
|
1899 |
+ |
@SuppressWarnings("FutureReturnValueIgnored") |
1900 |
+ |
void assertNullTaskSubmissionThrowsNullPointerException(Executor e) { |
1901 |
+ |
try { |
1902 |
+ |
e.execute((Runnable) null); |
1903 |
+ |
shouldThrow(); |
1904 |
+ |
} catch (NullPointerException success) {} |
1905 |
+ |
|
1906 |
+ |
if (! (e instanceof ExecutorService)) return; |
1907 |
+ |
ExecutorService es = (ExecutorService) e; |
1908 |
+ |
try { |
1909 |
+ |
es.submit((Runnable) null); |
1910 |
+ |
shouldThrow(); |
1911 |
+ |
} catch (NullPointerException success) {} |
1912 |
+ |
try { |
1913 |
+ |
es.submit((Runnable) null, Boolean.TRUE); |
1914 |
+ |
shouldThrow(); |
1915 |
+ |
} catch (NullPointerException success) {} |
1916 |
+ |
try { |
1917 |
+ |
es.submit((Callable) null); |
1918 |
+ |
shouldThrow(); |
1919 |
+ |
} catch (NullPointerException success) {} |
1920 |
+ |
|
1921 |
+ |
if (! (e instanceof ScheduledExecutorService)) return; |
1922 |
+ |
ScheduledExecutorService ses = (ScheduledExecutorService) e; |
1923 |
+ |
try { |
1924 |
+ |
ses.schedule((Runnable) null, |
1925 |
+ |
randomTimeout(), randomTimeUnit()); |
1926 |
+ |
shouldThrow(); |
1927 |
+ |
} catch (NullPointerException success) {} |
1928 |
+ |
try { |
1929 |
+ |
ses.schedule((Callable) null, |
1930 |
+ |
randomTimeout(), randomTimeUnit()); |
1931 |
+ |
shouldThrow(); |
1932 |
+ |
} catch (NullPointerException success) {} |
1933 |
+ |
try { |
1934 |
+ |
ses.scheduleAtFixedRate((Runnable) null, |
1935 |
+ |
randomTimeout(), LONG_DELAY_MS, MILLISECONDS); |
1936 |
+ |
shouldThrow(); |
1937 |
+ |
} catch (NullPointerException success) {} |
1938 |
+ |
try { |
1939 |
+ |
ses.scheduleWithFixedDelay((Runnable) null, |
1940 |
+ |
randomTimeout(), LONG_DELAY_MS, MILLISECONDS); |
1941 |
+ |
shouldThrow(); |
1942 |
+ |
} catch (NullPointerException success) {} |
1943 |
+ |
} |
1944 |
+ |
|
1945 |
+ |
void setRejectedExecutionHandler( |
1946 |
+ |
ThreadPoolExecutor p, RejectedExecutionHandler handler) { |
1947 |
+ |
p.setRejectedExecutionHandler(handler); |
1948 |
+ |
assertSame(handler, p.getRejectedExecutionHandler()); |
1949 |
+ |
} |
1950 |
+ |
|
1951 |
+ |
void assertTaskSubmissionsAreRejected(ThreadPoolExecutor p) { |
1952 |
+ |
final RejectedExecutionHandler savedHandler = p.getRejectedExecutionHandler(); |
1953 |
+ |
final long savedTaskCount = p.getTaskCount(); |
1954 |
+ |
final long savedCompletedTaskCount = p.getCompletedTaskCount(); |
1955 |
+ |
final int savedQueueSize = p.getQueue().size(); |
1956 |
+ |
final boolean stock = (p.getClass().getClassLoader() == null); |
1957 |
+ |
|
1958 |
+ |
Runnable r = () -> {}; |
1959 |
+ |
Callable<Boolean> c = () -> Boolean.TRUE; |
1960 |
+ |
|
1961 |
+ |
class Recorder implements RejectedExecutionHandler { |
1962 |
+ |
public volatile Runnable r = null; |
1963 |
+ |
public volatile ThreadPoolExecutor p = null; |
1964 |
+ |
public void reset() { r = null; p = null; } |
1965 |
+ |
public void rejectedExecution(Runnable r, ThreadPoolExecutor p) { |
1966 |
+ |
assertNull(this.r); |
1967 |
+ |
assertNull(this.p); |
1968 |
+ |
this.r = r; |
1969 |
+ |
this.p = p; |
1970 |
+ |
} |
1971 |
+ |
} |
1972 |
+ |
|
1973 |
+ |
// check custom handler is invoked exactly once per task |
1974 |
+ |
Recorder recorder = new Recorder(); |
1975 |
+ |
setRejectedExecutionHandler(p, recorder); |
1976 |
+ |
for (int i = 2; i--> 0; ) { |
1977 |
+ |
recorder.reset(); |
1978 |
+ |
p.execute(r); |
1979 |
+ |
if (stock && p.getClass() == ThreadPoolExecutor.class) |
1980 |
+ |
assertSame(r, recorder.r); |
1981 |
+ |
assertSame(p, recorder.p); |
1982 |
+ |
|
1983 |
+ |
recorder.reset(); |
1984 |
+ |
assertFalse(p.submit(r).isDone()); |
1985 |
+ |
if (stock) assertTrue(!((FutureTask) recorder.r).isDone()); |
1986 |
+ |
assertSame(p, recorder.p); |
1987 |
+ |
|
1988 |
+ |
recorder.reset(); |
1989 |
+ |
assertFalse(p.submit(r, Boolean.TRUE).isDone()); |
1990 |
+ |
if (stock) assertTrue(!((FutureTask) recorder.r).isDone()); |
1991 |
+ |
assertSame(p, recorder.p); |
1992 |
+ |
|
1993 |
+ |
recorder.reset(); |
1994 |
+ |
assertFalse(p.submit(c).isDone()); |
1995 |
+ |
if (stock) assertTrue(!((FutureTask) recorder.r).isDone()); |
1996 |
+ |
assertSame(p, recorder.p); |
1997 |
+ |
|
1998 |
+ |
if (p instanceof ScheduledExecutorService) { |
1999 |
+ |
ScheduledExecutorService s = (ScheduledExecutorService) p; |
2000 |
+ |
ScheduledFuture<?> future; |
2001 |
+ |
|
2002 |
+ |
recorder.reset(); |
2003 |
+ |
future = s.schedule(r, randomTimeout(), randomTimeUnit()); |
2004 |
+ |
assertFalse(future.isDone()); |
2005 |
+ |
if (stock) assertTrue(!((FutureTask) recorder.r).isDone()); |
2006 |
+ |
assertSame(p, recorder.p); |
2007 |
+ |
|
2008 |
+ |
recorder.reset(); |
2009 |
+ |
future = s.schedule(c, randomTimeout(), randomTimeUnit()); |
2010 |
+ |
assertFalse(future.isDone()); |
2011 |
+ |
if (stock) assertTrue(!((FutureTask) recorder.r).isDone()); |
2012 |
+ |
assertSame(p, recorder.p); |
2013 |
+ |
|
2014 |
+ |
recorder.reset(); |
2015 |
+ |
future = s.scheduleAtFixedRate(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS); |
2016 |
+ |
assertFalse(future.isDone()); |
2017 |
+ |
if (stock) assertTrue(!((FutureTask) recorder.r).isDone()); |
2018 |
+ |
assertSame(p, recorder.p); |
2019 |
+ |
|
2020 |
+ |
recorder.reset(); |
2021 |
+ |
future = s.scheduleWithFixedDelay(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS); |
2022 |
+ |
assertFalse(future.isDone()); |
2023 |
+ |
if (stock) assertTrue(!((FutureTask) recorder.r).isDone()); |
2024 |
+ |
assertSame(p, recorder.p); |
2025 |
+ |
} |
2026 |
+ |
} |
2027 |
+ |
|
2028 |
+ |
// Checking our custom handler above should be sufficient, but |
2029 |
+ |
// we add some integration tests of standard handlers. |
2030 |
+ |
final AtomicReference<Thread> thread = new AtomicReference<>(); |
2031 |
+ |
final Runnable setThread = () -> thread.set(Thread.currentThread()); |
2032 |
+ |
|
2033 |
+ |
setRejectedExecutionHandler(p, new ThreadPoolExecutor.AbortPolicy()); |
2034 |
+ |
try { |
2035 |
+ |
p.execute(setThread); |
2036 |
+ |
shouldThrow(); |
2037 |
+ |
} catch (RejectedExecutionException success) {} |
2038 |
+ |
assertNull(thread.get()); |
2039 |
+ |
|
2040 |
+ |
setRejectedExecutionHandler(p, new ThreadPoolExecutor.DiscardPolicy()); |
2041 |
+ |
p.execute(setThread); |
2042 |
+ |
assertNull(thread.get()); |
2043 |
+ |
|
2044 |
+ |
setRejectedExecutionHandler(p, new ThreadPoolExecutor.CallerRunsPolicy()); |
2045 |
+ |
p.execute(setThread); |
2046 |
+ |
if (p.isShutdown()) |
2047 |
+ |
assertNull(thread.get()); |
2048 |
+ |
else |
2049 |
+ |
assertSame(Thread.currentThread(), thread.get()); |
2050 |
+ |
|
2051 |
+ |
setRejectedExecutionHandler(p, savedHandler); |
2052 |
+ |
|
2053 |
+ |
// check that pool was not perturbed by handlers |
2054 |
+ |
assertEquals(savedTaskCount, p.getTaskCount()); |
2055 |
+ |
assertEquals(savedCompletedTaskCount, p.getCompletedTaskCount()); |
2056 |
+ |
assertEquals(savedQueueSize, p.getQueue().size()); |
2057 |
+ |
} |
2058 |
+ |
|
2059 |
+ |
void assertCollectionsEquals(Collection<?> x, Collection<?> y) { |
2060 |
+ |
assertEquals(x, y); |
2061 |
+ |
assertEquals(y, x); |
2062 |
+ |
assertEquals(x.isEmpty(), y.isEmpty()); |
2063 |
+ |
assertEquals(x.size(), y.size()); |
2064 |
+ |
if (x instanceof List) { |
2065 |
+ |
assertEquals(x.toString(), y.toString()); |
2066 |
+ |
} |
2067 |
+ |
if (x instanceof List || x instanceof Set) { |
2068 |
+ |
assertEquals(x.hashCode(), y.hashCode()); |
2069 |
+ |
} |
2070 |
+ |
if (x instanceof List || x instanceof Deque) { |
2071 |
+ |
assertTrue(Arrays.equals(x.toArray(), y.toArray())); |
2072 |
+ |
assertTrue(Arrays.equals(x.toArray(new Object[0]), |
2073 |
+ |
y.toArray(new Object[0]))); |
2074 |
+ |
} |
2075 |
+ |
} |
2076 |
+ |
|
2077 |
+ |
/** |
2078 |
+ |
* A weaker form of assertCollectionsEquals which does not insist |
2079 |
+ |
* that the two collections satisfy Object#equals(Object), since |
2080 |
+ |
* they may use identity semantics as Deques do. |
2081 |
+ |
*/ |
2082 |
+ |
void assertCollectionsEquivalent(Collection<?> x, Collection<?> y) { |
2083 |
+ |
if (x instanceof List || x instanceof Set) |
2084 |
+ |
assertCollectionsEquals(x, y); |
2085 |
+ |
else { |
2086 |
+ |
assertEquals(x.isEmpty(), y.isEmpty()); |
2087 |
+ |
assertEquals(x.size(), y.size()); |
2088 |
+ |
assertEquals(new HashSet(x), new HashSet(y)); |
2089 |
+ |
if (x instanceof Deque) { |
2090 |
+ |
assertTrue(Arrays.equals(x.toArray(), y.toArray())); |
2091 |
+ |
assertTrue(Arrays.equals(x.toArray(new Object[0]), |
2092 |
+ |
y.toArray(new Object[0]))); |
2093 |
+ |
} |
2094 |
+ |
} |
2095 |
+ |
} |
2096 |
|
} |