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 |
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 |
+ |
/* |
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; |
49 |
|
import java.io.ObjectInputStream; |
50 |
|
import java.io.ObjectOutputStream; |
51 |
|
import java.lang.management.ManagementFactory; |
52 |
+ |
import java.lang.management.LockInfo; |
53 |
|
import java.lang.management.ThreadInfo; |
54 |
|
import java.lang.management.ThreadMXBean; |
55 |
|
import java.lang.reflect.Constructor; |
56 |
|
import java.lang.reflect.Method; |
57 |
|
import java.lang.reflect.Modifier; |
23 |
– |
import java.nio.file.Files; |
24 |
– |
import java.nio.file.Paths; |
58 |
|
import java.security.CodeSource; |
59 |
|
import java.security.Permission; |
60 |
|
import java.security.PermissionCollection; |
64 |
|
import java.security.SecurityPermission; |
65 |
|
import java.util.ArrayList; |
66 |
|
import java.util.Arrays; |
67 |
+ |
import java.util.Collection; |
68 |
+ |
import java.util.Collections; |
69 |
|
import java.util.Date; |
70 |
+ |
import java.util.Deque; |
71 |
|
import java.util.Enumeration; |
72 |
+ |
import java.util.HashSet; |
73 |
|
import java.util.Iterator; |
74 |
|
import java.util.List; |
75 |
|
import java.util.NoSuchElementException; |
76 |
|
import java.util.PropertyPermission; |
77 |
+ |
import java.util.Queue; |
78 |
+ |
import java.util.Set; |
79 |
|
import java.util.concurrent.BlockingQueue; |
80 |
|
import java.util.concurrent.Callable; |
81 |
|
import java.util.concurrent.CountDownLatch; |
82 |
|
import java.util.concurrent.CyclicBarrier; |
83 |
|
import java.util.concurrent.ExecutionException; |
84 |
+ |
import java.util.concurrent.Executor; |
85 |
|
import java.util.concurrent.Executors; |
86 |
|
import java.util.concurrent.ExecutorService; |
87 |
|
import java.util.concurrent.ForkJoinPool; |
88 |
|
import java.util.concurrent.Future; |
89 |
+ |
import java.util.concurrent.FutureTask; |
90 |
|
import java.util.concurrent.RecursiveAction; |
91 |
|
import java.util.concurrent.RecursiveTask; |
92 |
+ |
import java.util.concurrent.RejectedExecutionException; |
93 |
|
import java.util.concurrent.RejectedExecutionHandler; |
94 |
|
import java.util.concurrent.Semaphore; |
95 |
+ |
import java.util.concurrent.ScheduledExecutorService; |
96 |
+ |
import java.util.concurrent.ScheduledFuture; |
97 |
+ |
import java.util.concurrent.SynchronousQueue; |
98 |
|
import java.util.concurrent.ThreadFactory; |
99 |
+ |
import java.util.concurrent.ThreadLocalRandom; |
100 |
|
import java.util.concurrent.ThreadPoolExecutor; |
101 |
+ |
import java.util.concurrent.TimeUnit; |
102 |
|
import java.util.concurrent.TimeoutException; |
103 |
+ |
import java.util.concurrent.atomic.AtomicBoolean; |
104 |
|
import java.util.concurrent.atomic.AtomicReference; |
57 |
– |
import java.util.regex.Matcher; |
105 |
|
import java.util.regex.Pattern; |
106 |
|
|
60 |
– |
import junit.framework.AssertionFailedError; |
107 |
|
import junit.framework.Test; |
108 |
|
import junit.framework.TestCase; |
109 |
|
import junit.framework.TestResult; |
119 |
|
* |
120 |
|
* <ol> |
121 |
|
* |
122 |
< |
* <li>All assertions in code running in generated threads must use |
123 |
< |
* the forms {@link #threadFail}, {@link #threadAssertTrue}, {@link |
124 |
< |
* #threadAssertEquals}, or {@link #threadAssertNull}, (not |
125 |
< |
* {@code fail}, {@code assertTrue}, etc.) It is OK (but not |
126 |
< |
* particularly recommended) for other code to use these forms too. |
127 |
< |
* Only the most typically used JUnit assertion methods are defined |
128 |
< |
* this way, but enough to live with. |
122 |
> |
* <li>All code not running in the main test thread (manually spawned threads |
123 |
> |
* or the common fork join pool) must be checked for failure (and completion!). |
124 |
> |
* Mechanisms that can be used to ensure this are: |
125 |
> |
* <ol> |
126 |
> |
* <li>Signalling via a synchronizer like AtomicInteger or CountDownLatch |
127 |
> |
* that the task completed normally, which is checked before returning from |
128 |
> |
* the test method in the main thread. |
129 |
> |
* <li>Using the forms {@link #threadFail}, {@link #threadAssertTrue}, |
130 |
> |
* or {@link #threadAssertNull}, (not {@code fail}, {@code assertTrue}, etc.) |
131 |
> |
* Only the most typically used JUnit assertion methods are defined |
132 |
> |
* this way, but enough to live with. |
133 |
> |
* <li>Recording failure explicitly using {@link #threadUnexpectedException} |
134 |
> |
* or {@link #threadRecordFailure}. |
135 |
> |
* <li>Using a wrapper like CheckedRunnable that uses one the mechanisms above. |
136 |
> |
* </ol> |
137 |
|
* |
138 |
|
* <li>If you override {@link #setUp} or {@link #tearDown}, make sure |
139 |
|
* to invoke {@code super.setUp} and {@code super.tearDown} within |
151 |
|
* but even so, if there is ever any doubt, they can all be increased |
152 |
|
* in one spot to rerun tests on slower platforms. |
153 |
|
* |
154 |
+ |
* Class Item is used for elements of collections and related |
155 |
+ |
* purposes. Many tests rely on their keys being equal to ints. To |
156 |
+ |
* check these, methods mustEqual, mustContain, etc adapt the JUnit |
157 |
+ |
* assert methods to intercept ints. |
158 |
+ |
* |
159 |
|
* <li>All threads generated must be joined inside each test case |
160 |
|
* method (or {@code fail} to do so) before returning from the |
161 |
|
* method. The {@code joinPool} method can be used to do this when |
195 |
|
* </ul> |
196 |
|
*/ |
197 |
|
public class JSR166TestCase extends TestCase { |
198 |
+ |
// No longer run with custom securityManagers |
199 |
|
private static final boolean useSecurityManager = |
200 |
< |
Boolean.getBoolean("jsr166.useSecurityManager"); |
200 |
> |
Boolean.getBoolean("jsr166.useSecurityManager"); |
201 |
|
|
202 |
|
protected static final boolean expensiveTests = |
203 |
|
Boolean.getBoolean("jsr166.expensiveTests"); |
235 |
|
private static final int suiteRuns = |
236 |
|
Integer.getInteger("jsr166.suiteRuns", 1); |
237 |
|
|
238 |
+ |
/** |
239 |
+ |
* Returns the value of the system property, or NaN if not defined. |
240 |
+ |
*/ |
241 |
+ |
private static float systemPropertyValue(String name) { |
242 |
+ |
String floatString = System.getProperty(name); |
243 |
+ |
if (floatString == null) |
244 |
+ |
return Float.NaN; |
245 |
+ |
try { |
246 |
+ |
return Float.parseFloat(floatString); |
247 |
+ |
} catch (NumberFormatException ex) { |
248 |
+ |
throw new IllegalArgumentException( |
249 |
+ |
String.format("Bad float value in system property %s=%s", |
250 |
+ |
name, floatString)); |
251 |
+ |
} |
252 |
+ |
} |
253 |
+ |
|
254 |
+ |
private static final ThreadMXBean THREAD_MXBEAN |
255 |
+ |
= ManagementFactory.getThreadMXBean(); |
256 |
+ |
|
257 |
+ |
/** |
258 |
+ |
* The scaling factor to apply to standard delays used in tests. |
259 |
+ |
* May be initialized from any of: |
260 |
+ |
* - the "jsr166.delay.factor" system property |
261 |
+ |
* - the "test.timeout.factor" system property (as used by jtreg) |
262 |
+ |
* See: http://openjdk.java.net/jtreg/tag-spec.html |
263 |
+ |
* - hard-coded fuzz factor when using a known slowpoke VM |
264 |
+ |
*/ |
265 |
+ |
private static final float delayFactor = delayFactor(); |
266 |
+ |
|
267 |
+ |
private static float delayFactor() { |
268 |
+ |
float x; |
269 |
+ |
if (!Float.isNaN(x = systemPropertyValue("jsr166.delay.factor"))) |
270 |
+ |
return x; |
271 |
+ |
if (!Float.isNaN(x = systemPropertyValue("test.timeout.factor"))) |
272 |
+ |
return x; |
273 |
+ |
String prop = System.getProperty("java.vm.version"); |
274 |
+ |
if (prop != null && prop.matches(".*debug.*")) |
275 |
+ |
return 4.0f; // How much slower is fastdebug than product?! |
276 |
+ |
return 1.0f; |
277 |
+ |
} |
278 |
+ |
|
279 |
|
public JSR166TestCase() { super(); } |
280 |
|
public JSR166TestCase(String name) { super(name); } |
281 |
|
|
295 |
|
static volatile TestCase currentTestCase; |
296 |
|
// static volatile int currentRun = 0; |
297 |
|
static { |
298 |
< |
Runnable checkForWedgedTest = new Runnable() { public void run() { |
298 |
> |
Runnable wedgedTestDetector = new Runnable() { public void run() { |
299 |
|
// Avoid spurious reports with enormous runsPerTest. |
300 |
|
// A single test case run should never take more than 1 second. |
301 |
|
// But let's cap it at the high end too ... |
302 |
< |
final int timeoutMinutes = |
303 |
< |
Math.min(15, Math.max(runsPerTest / 60, 1)); |
302 |
> |
final int timeoutMinutesMin = Math.max(runsPerTest / 60, 1) |
303 |
> |
* Math.max((int) delayFactor, 1); |
304 |
> |
final int timeoutMinutes = Math.min(15, timeoutMinutesMin); |
305 |
|
for (TestCase lastTestCase = currentTestCase;;) { |
306 |
|
try { MINUTES.sleep(timeoutMinutes); } |
307 |
|
catch (InterruptedException unexpected) { break; } |
321 |
|
} |
322 |
|
lastTestCase = currentTestCase; |
323 |
|
}}}; |
324 |
< |
Thread thread = new Thread(checkForWedgedTest, "checkForWedgedTest"); |
324 |
> |
Thread thread = new Thread(wedgedTestDetector, "WedgedTestDetector"); |
325 |
|
thread.setDaemon(true); |
326 |
|
thread.start(); |
327 |
|
} |
328 |
|
|
329 |
|
// public static String cpuModel() { |
330 |
|
// try { |
331 |
< |
// Matcher matcher = Pattern.compile("model name\\s*: (.*)") |
331 |
> |
// java.util.regex.Matcher matcher |
332 |
> |
// = Pattern.compile("model name\\s*: (.*)") |
333 |
|
// .matcher(new String( |
334 |
< |
// Files.readAllBytes(Paths.get("/proc/cpuinfo")), "UTF-8")); |
334 |
> |
// java.nio.file.Files.readAllBytes( |
335 |
> |
// java.nio.file.Paths.get("/proc/cpuinfo")), "UTF-8")); |
336 |
|
// matcher.find(); |
337 |
|
// return matcher.group(1); |
338 |
|
// } catch (Exception ex) { return null; } |
365 |
|
// Never report first run of any test; treat it as a |
366 |
|
// warmup run, notably to trigger all needed classloading, |
367 |
|
if (i > 0) |
368 |
< |
System.out.printf("%n%s: %d%n", toString(), elapsedMillis); |
368 |
> |
System.out.printf("%s: %d%n", toString(), elapsedMillis); |
369 |
|
} |
370 |
|
} |
371 |
|
|
408 |
|
* Runs all unit tests in the given test suite. |
409 |
|
* Actual behavior influenced by jsr166.* system properties. |
410 |
|
*/ |
411 |
+ |
@SuppressWarnings("removal") |
412 |
|
static void main(Test suite, String[] args) { |
413 |
|
if (useSecurityManager) { |
414 |
|
System.err.println("Setting a permissive security manager"); |
415 |
|
Policy.setPolicy(permissivePolicy()); |
416 |
< |
System.setSecurityManager(new SecurityManager()); |
416 |
> |
try { |
417 |
> |
System.setSecurityManager(new SecurityManager()); |
418 |
> |
} catch(Throwable ok) { // failure OK during deprecation |
419 |
> |
} |
420 |
|
} |
421 |
|
for (int i = 0; i < suiteRuns; i++) { |
422 |
|
TestResult result = newPithyTestRunner().doRun(suite); |
445 |
|
for (String testClassName : testClassNames) { |
446 |
|
try { |
447 |
|
Class<?> testClass = Class.forName(testClassName); |
448 |
< |
Method m = testClass.getDeclaredMethod("suite", |
341 |
< |
new Class<?>[0]); |
448 |
> |
Method m = testClass.getDeclaredMethod("suite"); |
449 |
|
suite.addTest(newTestSuite((Test)m.invoke(null))); |
450 |
< |
} catch (Exception e) { |
451 |
< |
throw new Error("Missing test class", e); |
450 |
> |
} catch (ReflectiveOperationException e) { |
451 |
> |
throw new AssertionError("Missing test class", e); |
452 |
|
} |
453 |
|
} |
454 |
|
} |
457 |
|
public static final String JAVA_SPECIFICATION_VERSION; |
458 |
|
static { |
459 |
|
try { |
460 |
< |
JAVA_CLASS_VERSION = java.security.AccessController.doPrivileged( |
460 |
> |
@SuppressWarnings("removal") double jcv = |
461 |
> |
java.security.AccessController.doPrivileged( |
462 |
|
new java.security.PrivilegedAction<Double>() { |
463 |
|
public Double run() { |
464 |
|
return Double.valueOf(System.getProperty("java.class.version"));}}); |
465 |
< |
JAVA_SPECIFICATION_VERSION = java.security.AccessController.doPrivileged( |
465 |
> |
JAVA_CLASS_VERSION = jcv; |
466 |
> |
@SuppressWarnings("removal") String jsv = |
467 |
> |
java.security.AccessController.doPrivileged( |
468 |
|
new java.security.PrivilegedAction<String>() { |
469 |
|
public String run() { |
470 |
|
return System.getProperty("java.specification.version");}}); |
471 |
+ |
JAVA_SPECIFICATION_VERSION = jsv; |
472 |
|
} catch (Throwable t) { |
473 |
|
throw new Error(t); |
474 |
|
} |
475 |
|
} |
476 |
|
|
477 |
< |
public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; } |
478 |
< |
public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; } |
479 |
< |
public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; } |
480 |
< |
public static boolean atLeastJava9() { |
481 |
< |
return JAVA_CLASS_VERSION >= 53.0 |
482 |
< |
// As of 2015-09, java9 still uses 52.0 class file version |
483 |
< |
|| JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?(9|[0-9][0-9])$"); |
484 |
< |
} |
485 |
< |
public static boolean atLeastJava10() { |
486 |
< |
return JAVA_CLASS_VERSION >= 54.0 |
487 |
< |
|| JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?[0-9][0-9]$"); |
488 |
< |
} |
477 |
> |
public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; } |
478 |
> |
public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; } |
479 |
> |
public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; } |
480 |
> |
public static boolean atLeastJava9() { return JAVA_CLASS_VERSION >= 53.0; } |
481 |
> |
public static boolean atLeastJava10() { return JAVA_CLASS_VERSION >= 54.0; } |
482 |
> |
public static boolean atLeastJava11() { return JAVA_CLASS_VERSION >= 55.0; } |
483 |
> |
public static boolean atLeastJava12() { return JAVA_CLASS_VERSION >= 56.0; } |
484 |
> |
public static boolean atLeastJava13() { return JAVA_CLASS_VERSION >= 57.0; } |
485 |
> |
public static boolean atLeastJava14() { return JAVA_CLASS_VERSION >= 58.0; } |
486 |
> |
public static boolean atLeastJava15() { return JAVA_CLASS_VERSION >= 59.0; } |
487 |
> |
public static boolean atLeastJava16() { return JAVA_CLASS_VERSION >= 60.0; } |
488 |
> |
public static boolean atLeastJava17() { return JAVA_CLASS_VERSION >= 61.0; } |
489 |
|
|
490 |
|
/** |
491 |
|
* Collects all JSR166 unit tests as one suite. |
506 |
|
AbstractQueuedLongSynchronizerTest.suite(), |
507 |
|
ArrayBlockingQueueTest.suite(), |
508 |
|
ArrayDequeTest.suite(), |
509 |
+ |
ArrayListTest.suite(), |
510 |
|
AtomicBooleanTest.suite(), |
511 |
|
AtomicIntegerArrayTest.suite(), |
512 |
|
AtomicIntegerFieldUpdaterTest.suite(), |
529 |
|
CopyOnWriteArrayListTest.suite(), |
530 |
|
CopyOnWriteArraySetTest.suite(), |
531 |
|
CountDownLatchTest.suite(), |
532 |
+ |
CountedCompleterTest.suite(), |
533 |
|
CyclicBarrierTest.suite(), |
534 |
|
DelayQueueTest.suite(), |
535 |
|
EntryTest.suite(), |
537 |
|
ExecutorsTest.suite(), |
538 |
|
ExecutorCompletionServiceTest.suite(), |
539 |
|
FutureTaskTest.suite(), |
540 |
+ |
HashtableTest.suite(), |
541 |
|
LinkedBlockingDequeTest.suite(), |
542 |
|
LinkedBlockingQueueTest.suite(), |
543 |
|
LinkedListTest.suite(), |
559 |
|
TreeMapTest.suite(), |
560 |
|
TreeSetTest.suite(), |
561 |
|
TreeSubMapTest.suite(), |
562 |
< |
TreeSubSetTest.suite()); |
562 |
> |
TreeSubSetTest.suite(), |
563 |
> |
VectorTest.suite()); |
564 |
|
|
565 |
|
// Java8+ test classes |
566 |
|
if (atLeastJava8()) { |
567 |
|
String[] java8TestClassNames = { |
568 |
+ |
"ArrayDeque8Test", |
569 |
|
"Atomic8Test", |
570 |
|
"CompletableFutureTest", |
571 |
|
"ConcurrentHashMap8Test", |
572 |
< |
"CountedCompleterTest", |
572 |
> |
"CountedCompleter8Test", |
573 |
|
"DoubleAccumulatorTest", |
574 |
|
"DoubleAdderTest", |
575 |
|
"ForkJoinPool8Test", |
576 |
|
"ForkJoinTask8Test", |
577 |
+ |
"HashMapTest", |
578 |
+ |
"LinkedBlockingDeque8Test", |
579 |
+ |
"LinkedBlockingQueue8Test", |
580 |
+ |
"LinkedHashMapTest", |
581 |
|
"LongAccumulatorTest", |
582 |
|
"LongAdderTest", |
583 |
|
"SplittableRandomTest", |
584 |
|
"StampedLockTest", |
585 |
|
"SubmissionPublisherTest", |
586 |
|
"ThreadLocalRandom8Test", |
587 |
+ |
"TimeUnit8Test", |
588 |
|
}; |
589 |
|
addNamedTestClasses(suite, java8TestClassNames); |
590 |
|
} |
592 |
|
// Java9+ test classes |
593 |
|
if (atLeastJava9()) { |
594 |
|
String[] java9TestClassNames = { |
595 |
< |
// Currently empty, but expecting varhandle tests |
595 |
> |
"AtomicBoolean9Test", |
596 |
> |
"AtomicInteger9Test", |
597 |
> |
"AtomicIntegerArray9Test", |
598 |
> |
"AtomicLong9Test", |
599 |
> |
"AtomicLongArray9Test", |
600 |
> |
"AtomicReference9Test", |
601 |
> |
"AtomicReferenceArray9Test", |
602 |
> |
"ExecutorCompletionService9Test", |
603 |
> |
"ForkJoinPool9Test", |
604 |
|
}; |
605 |
|
addNamedTestClasses(suite, java9TestClassNames); |
606 |
|
} |
607 |
|
|
608 |
+ |
if (atLeastJava17()) { |
609 |
+ |
String[] java17TestClassNames = { |
610 |
+ |
"ForkJoinPool19Test", |
611 |
+ |
}; |
612 |
+ |
addNamedTestClasses(suite, java17TestClassNames); |
613 |
+ |
} |
614 |
|
return suite; |
615 |
|
} |
616 |
|
|
617 |
|
/** Returns list of junit-style test method names in given class. */ |
618 |
|
public static ArrayList<String> testMethodNames(Class<?> testClass) { |
619 |
|
Method[] methods = testClass.getDeclaredMethods(); |
620 |
< |
ArrayList<String> names = new ArrayList<String>(methods.length); |
620 |
> |
ArrayList<String> names = new ArrayList<>(methods.length); |
621 |
|
for (Method method : methods) { |
622 |
|
if (method.getName().startsWith("test") |
623 |
|
&& Modifier.isPublic(method.getModifiers()) |
644 |
|
for (String methodName : testMethodNames(testClass)) |
645 |
|
suite.addTest((Test) c.newInstance(data, methodName)); |
646 |
|
return suite; |
647 |
< |
} catch (Exception e) { |
648 |
< |
throw new Error(e); |
647 |
> |
} catch (ReflectiveOperationException e) { |
648 |
> |
throw new AssertionError(e); |
649 |
|
} |
650 |
|
} |
651 |
|
|
661 |
|
if (atLeastJava8()) { |
662 |
|
String name = testClass.getName(); |
663 |
|
String name8 = name.replaceAll("Test$", "8Test"); |
664 |
< |
if (name.equals(name8)) throw new Error(name); |
664 |
> |
if (name.equals(name8)) throw new AssertionError(name); |
665 |
|
try { |
666 |
|
return (Test) |
667 |
|
Class.forName(name8) |
668 |
< |
.getMethod("testSuite", new Class[] { dataClass }) |
668 |
> |
.getMethod("testSuite", dataClass) |
669 |
|
.invoke(null, data); |
670 |
< |
} catch (Exception e) { |
671 |
< |
throw new Error(e); |
670 |
> |
} catch (ReflectiveOperationException e) { |
671 |
> |
throw new AssertionError(e); |
672 |
|
} |
673 |
|
} else { |
674 |
|
return new TestSuite(); |
683 |
|
public static long LONG_DELAY_MS; |
684 |
|
|
685 |
|
/** |
686 |
< |
* Returns the shortest timed delay. This could |
687 |
< |
* be reimplemented to use for example a Property. |
686 |
> |
* A delay significantly longer than LONG_DELAY_MS. |
687 |
> |
* Use this in a thread that is waited for via awaitTermination(Thread). |
688 |
> |
*/ |
689 |
> |
public static long LONGER_DELAY_MS; |
690 |
> |
|
691 |
> |
private static final long RANDOM_TIMEOUT; |
692 |
> |
private static final long RANDOM_EXPIRED_TIMEOUT; |
693 |
> |
private static final TimeUnit RANDOM_TIMEUNIT; |
694 |
> |
static { |
695 |
> |
ThreadLocalRandom rnd = ThreadLocalRandom.current(); |
696 |
> |
long[] timeouts = { Long.MIN_VALUE, -1, 0, 1, Long.MAX_VALUE }; |
697 |
> |
RANDOM_TIMEOUT = timeouts[rnd.nextInt(timeouts.length)]; |
698 |
> |
RANDOM_EXPIRED_TIMEOUT = timeouts[rnd.nextInt(3)]; |
699 |
> |
TimeUnit[] timeUnits = TimeUnit.values(); |
700 |
> |
RANDOM_TIMEUNIT = timeUnits[rnd.nextInt(timeUnits.length)]; |
701 |
> |
} |
702 |
> |
|
703 |
> |
/** |
704 |
> |
* Returns a timeout for use when any value at all will do. |
705 |
> |
*/ |
706 |
> |
static long randomTimeout() { return RANDOM_TIMEOUT; } |
707 |
> |
|
708 |
> |
/** |
709 |
> |
* Returns a timeout that means "no waiting", i.e. not positive. |
710 |
> |
*/ |
711 |
> |
static long randomExpiredTimeout() { return RANDOM_EXPIRED_TIMEOUT; } |
712 |
> |
|
713 |
> |
/** |
714 |
> |
* Returns a random non-null TimeUnit. |
715 |
> |
*/ |
716 |
> |
static TimeUnit randomTimeUnit() { return RANDOM_TIMEUNIT; } |
717 |
> |
|
718 |
> |
/** |
719 |
> |
* Returns a random boolean; a "coin flip". |
720 |
> |
*/ |
721 |
> |
static boolean randomBoolean() { |
722 |
> |
return ThreadLocalRandom.current().nextBoolean(); |
723 |
> |
} |
724 |
> |
|
725 |
> |
/** |
726 |
> |
* Returns a random element from given choices. |
727 |
> |
*/ |
728 |
> |
<T> T chooseRandomly(List<T> choices) { |
729 |
> |
return choices.get(ThreadLocalRandom.current().nextInt(choices.size())); |
730 |
> |
} |
731 |
> |
|
732 |
> |
/** |
733 |
> |
* Returns a random element from given choices. |
734 |
> |
*/ |
735 |
> |
@SuppressWarnings("unchecked") |
736 |
> |
<T> T chooseRandomly(T... choices) { |
737 |
> |
return choices[ThreadLocalRandom.current().nextInt(choices.length)]; |
738 |
> |
} |
739 |
> |
|
740 |
> |
/** |
741 |
> |
* Returns the shortest timed delay. This can be scaled up for |
742 |
> |
* slow machines using the jsr166.delay.factor system property, |
743 |
> |
* or via jtreg's -timeoutFactor: flag. |
744 |
> |
* http://openjdk.java.net/jtreg/command-help.html |
745 |
|
*/ |
746 |
|
protected long getShortDelay() { |
747 |
< |
return 50; |
747 |
> |
return (long) (50 * delayFactor); |
748 |
|
} |
749 |
|
|
750 |
|
/** |
755 |
|
SMALL_DELAY_MS = SHORT_DELAY_MS * 5; |
756 |
|
MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10; |
757 |
|
LONG_DELAY_MS = SHORT_DELAY_MS * 200; |
758 |
+ |
LONGER_DELAY_MS = 2 * LONG_DELAY_MS; |
759 |
|
} |
760 |
|
|
761 |
+ |
private static final long TIMEOUT_DELAY_MS |
762 |
+ |
= (long) (12.0 * Math.cbrt(delayFactor)); |
763 |
+ |
|
764 |
|
/** |
765 |
< |
* Returns a timeout in milliseconds to be used in tests that |
766 |
< |
* verify that operations block or time out. |
765 |
> |
* Returns a timeout in milliseconds to be used in tests that verify |
766 |
> |
* that operations block or time out. We want this to be longer |
767 |
> |
* than the OS scheduling quantum, but not too long, so don't scale |
768 |
> |
* linearly with delayFactor; we use "crazy" cube root instead. |
769 |
|
*/ |
770 |
< |
long timeoutMillis() { |
771 |
< |
return SHORT_DELAY_MS / 4; |
770 |
> |
static long timeoutMillis() { |
771 |
> |
return TIMEOUT_DELAY_MS; |
772 |
|
} |
773 |
|
|
774 |
|
/** |
784 |
|
* The first exception encountered if any threadAssertXXX method fails. |
785 |
|
*/ |
786 |
|
private final AtomicReference<Throwable> threadFailure |
787 |
< |
= new AtomicReference<Throwable>(null); |
787 |
> |
= new AtomicReference<>(null); |
788 |
|
|
789 |
|
/** |
790 |
|
* Records an exception so that it can be rethrown later in the test |
794 |
|
*/ |
795 |
|
public void threadRecordFailure(Throwable t) { |
796 |
|
System.err.println(t); |
797 |
< |
dumpTestThreads(); |
798 |
< |
threadFailure.compareAndSet(null, t); |
797 |
> |
if (threadFailure.compareAndSet(null, t)) |
798 |
> |
dumpTestThreads(); |
799 |
|
} |
800 |
|
|
801 |
|
public void setUp() { |
806 |
|
String msg = toString() + ": " + String.format(format, args); |
807 |
|
System.err.println(msg); |
808 |
|
dumpTestThreads(); |
809 |
< |
throw new AssertionFailedError(msg); |
809 |
> |
throw new AssertionError(msg); |
810 |
|
} |
811 |
|
|
812 |
|
/** |
827 |
|
throw (RuntimeException) t; |
828 |
|
else if (t instanceof Exception) |
829 |
|
throw (Exception) t; |
830 |
< |
else { |
831 |
< |
AssertionFailedError afe = |
634 |
< |
new AssertionFailedError(t.toString()); |
635 |
< |
afe.initCause(t); |
636 |
< |
throw afe; |
637 |
< |
} |
830 |
> |
else |
831 |
> |
throw new AssertionError(t.toString(), t); |
832 |
|
} |
833 |
|
|
834 |
|
if (Thread.interrupted()) |
862 |
|
|
863 |
|
/** |
864 |
|
* Just like fail(reason), but additionally recording (using |
865 |
< |
* threadRecordFailure) any AssertionFailedError thrown, so that |
866 |
< |
* the current testcase will fail. |
865 |
> |
* threadRecordFailure) any AssertionError thrown, so that the |
866 |
> |
* current testcase will fail. |
867 |
|
*/ |
868 |
|
public void threadFail(String reason) { |
869 |
|
try { |
870 |
|
fail(reason); |
871 |
< |
} catch (AssertionFailedError t) { |
872 |
< |
threadRecordFailure(t); |
873 |
< |
throw t; |
871 |
> |
} catch (AssertionError fail) { |
872 |
> |
threadRecordFailure(fail); |
873 |
> |
throw fail; |
874 |
|
} |
875 |
|
} |
876 |
|
|
877 |
|
/** |
878 |
|
* Just like assertTrue(b), but additionally recording (using |
879 |
< |
* threadRecordFailure) any AssertionFailedError thrown, so that |
880 |
< |
* the current testcase will fail. |
879 |
> |
* threadRecordFailure) any AssertionError thrown, so that the |
880 |
> |
* current testcase will fail. |
881 |
|
*/ |
882 |
|
public void threadAssertTrue(boolean b) { |
883 |
|
try { |
884 |
|
assertTrue(b); |
885 |
< |
} catch (AssertionFailedError t) { |
886 |
< |
threadRecordFailure(t); |
887 |
< |
throw t; |
885 |
> |
} catch (AssertionError fail) { |
886 |
> |
threadRecordFailure(fail); |
887 |
> |
throw fail; |
888 |
|
} |
889 |
|
} |
890 |
|
|
891 |
|
/** |
892 |
|
* Just like assertFalse(b), but additionally recording (using |
893 |
< |
* threadRecordFailure) any AssertionFailedError thrown, so that |
894 |
< |
* the current testcase will fail. |
893 |
> |
* threadRecordFailure) any AssertionError thrown, so that the |
894 |
> |
* current testcase will fail. |
895 |
|
*/ |
896 |
|
public void threadAssertFalse(boolean b) { |
897 |
|
try { |
898 |
|
assertFalse(b); |
899 |
< |
} catch (AssertionFailedError t) { |
900 |
< |
threadRecordFailure(t); |
901 |
< |
throw t; |
899 |
> |
} catch (AssertionError fail) { |
900 |
> |
threadRecordFailure(fail); |
901 |
> |
throw fail; |
902 |
|
} |
903 |
|
} |
904 |
|
|
905 |
|
/** |
906 |
|
* Just like assertNull(x), but additionally recording (using |
907 |
< |
* threadRecordFailure) any AssertionFailedError thrown, so that |
908 |
< |
* the current testcase will fail. |
907 |
> |
* threadRecordFailure) any AssertionError thrown, so that the |
908 |
> |
* current testcase will fail. |
909 |
|
*/ |
910 |
|
public void threadAssertNull(Object x) { |
911 |
|
try { |
912 |
|
assertNull(x); |
913 |
< |
} catch (AssertionFailedError t) { |
914 |
< |
threadRecordFailure(t); |
915 |
< |
throw t; |
913 |
> |
} catch (AssertionError fail) { |
914 |
> |
threadRecordFailure(fail); |
915 |
> |
throw fail; |
916 |
|
} |
917 |
|
} |
918 |
|
|
919 |
|
/** |
920 |
|
* Just like assertEquals(x, y), but additionally recording (using |
921 |
< |
* threadRecordFailure) any AssertionFailedError thrown, so that |
922 |
< |
* the current testcase will fail. |
921 |
> |
* threadRecordFailure) any AssertionError thrown, so that the |
922 |
> |
* current testcase will fail. |
923 |
|
*/ |
924 |
|
public void threadAssertEquals(long x, long y) { |
925 |
|
try { |
926 |
|
assertEquals(x, y); |
927 |
< |
} catch (AssertionFailedError t) { |
928 |
< |
threadRecordFailure(t); |
929 |
< |
throw t; |
927 |
> |
} catch (AssertionError fail) { |
928 |
> |
threadRecordFailure(fail); |
929 |
> |
throw fail; |
930 |
|
} |
931 |
|
} |
932 |
|
|
933 |
|
/** |
934 |
|
* Just like assertEquals(x, y), but additionally recording (using |
935 |
< |
* threadRecordFailure) any AssertionFailedError thrown, so that |
936 |
< |
* the current testcase will fail. |
935 |
> |
* threadRecordFailure) any AssertionError thrown, so that the |
936 |
> |
* current testcase will fail. |
937 |
|
*/ |
938 |
|
public void threadAssertEquals(Object x, Object y) { |
939 |
|
try { |
940 |
|
assertEquals(x, y); |
941 |
< |
} catch (AssertionFailedError fail) { |
941 |
> |
} catch (AssertionError fail) { |
942 |
|
threadRecordFailure(fail); |
943 |
|
throw fail; |
944 |
|
} catch (Throwable fail) { |
948 |
|
|
949 |
|
/** |
950 |
|
* Just like assertSame(x, y), but additionally recording (using |
951 |
< |
* threadRecordFailure) any AssertionFailedError thrown, so that |
952 |
< |
* the current testcase will fail. |
951 |
> |
* threadRecordFailure) any AssertionError thrown, so that the |
952 |
> |
* current testcase will fail. |
953 |
|
*/ |
954 |
|
public void threadAssertSame(Object x, Object y) { |
955 |
|
try { |
956 |
|
assertSame(x, y); |
957 |
< |
} catch (AssertionFailedError fail) { |
957 |
> |
} catch (AssertionError fail) { |
958 |
|
threadRecordFailure(fail); |
959 |
|
throw fail; |
960 |
|
} |
976 |
|
|
977 |
|
/** |
978 |
|
* Records the given exception using {@link #threadRecordFailure}, |
979 |
< |
* then rethrows the exception, wrapping it in an |
980 |
< |
* AssertionFailedError if necessary. |
979 |
> |
* then rethrows the exception, wrapping it in an AssertionError |
980 |
> |
* if necessary. |
981 |
|
*/ |
982 |
|
public void threadUnexpectedException(Throwable t) { |
983 |
|
threadRecordFailure(t); |
986 |
|
throw (RuntimeException) t; |
987 |
|
else if (t instanceof Error) |
988 |
|
throw (Error) t; |
989 |
< |
else { |
990 |
< |
AssertionFailedError afe = |
797 |
< |
new AssertionFailedError("unexpected exception: " + t); |
798 |
< |
afe.initCause(t); |
799 |
< |
throw afe; |
800 |
< |
} |
989 |
> |
else |
990 |
> |
throw new AssertionError("unexpected exception: " + t, t); |
991 |
|
} |
992 |
|
|
993 |
|
/** |
1055 |
|
}}; |
1056 |
|
} |
1057 |
|
|
1058 |
+ |
PoolCleaner cleaner(ExecutorService pool, AtomicBoolean flag) { |
1059 |
+ |
return new PoolCleanerWithReleaser(pool, releaser(flag)); |
1060 |
+ |
} |
1061 |
+ |
|
1062 |
+ |
Runnable releaser(final AtomicBoolean flag) { |
1063 |
+ |
return new Runnable() { public void run() { flag.set(true); }}; |
1064 |
+ |
} |
1065 |
+ |
|
1066 |
|
/** |
1067 |
|
* Waits out termination of a thread pool or fails doing so. |
1068 |
|
*/ |
1069 |
|
void joinPool(ExecutorService pool) { |
1070 |
|
try { |
1071 |
|
pool.shutdown(); |
1072 |
< |
if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS)) { |
1072 |
> |
if (!pool.awaitTermination(20 * LONG_DELAY_MS, MILLISECONDS)) { |
1073 |
|
try { |
1074 |
|
threadFail("ExecutorService " + pool + |
1075 |
|
" did not terminate in a timely manner"); |
1086 |
|
} |
1087 |
|
} |
1088 |
|
|
1089 |
< |
/** Like Runnable, but with the freedom to throw anything */ |
1089 |
> |
/** |
1090 |
> |
* Like Runnable, but with the freedom to throw anything. |
1091 |
> |
* junit folks had the same idea: |
1092 |
> |
* http://junit.org/junit5/docs/snapshot/api/org/junit/gen5/api/Executable.html |
1093 |
> |
*/ |
1094 |
|
interface Action { public void run() throws Throwable; } |
1095 |
|
|
1096 |
|
/** |
1116 |
|
} |
1117 |
|
} |
1118 |
|
|
1119 |
+ |
/** Returns true if thread info might be useful in a thread dump. */ |
1120 |
+ |
static boolean threadOfInterest(ThreadInfo info) { |
1121 |
+ |
final String name = info.getThreadName(); |
1122 |
+ |
String lockName; |
1123 |
+ |
if (name == null) |
1124 |
+ |
return true; |
1125 |
+ |
if (name.equals("Signal Dispatcher") |
1126 |
+ |
|| name.equals("WedgedTestDetector")) |
1127 |
+ |
return false; |
1128 |
+ |
if (name.equals("Reference Handler")) { |
1129 |
+ |
// Reference Handler stacktrace changed in JDK-8156500 |
1130 |
+ |
StackTraceElement[] stackTrace; String methodName; |
1131 |
+ |
if ((stackTrace = info.getStackTrace()) != null |
1132 |
+ |
&& stackTrace.length > 0 |
1133 |
+ |
&& (methodName = stackTrace[0].getMethodName()) != null |
1134 |
+ |
&& methodName.equals("waitForReferencePendingList")) |
1135 |
+ |
return false; |
1136 |
+ |
// jdk8 Reference Handler stacktrace |
1137 |
+ |
if ((lockName = info.getLockName()) != null |
1138 |
+ |
&& lockName.startsWith("java.lang.ref")) |
1139 |
+ |
return false; |
1140 |
+ |
} |
1141 |
+ |
if ((name.equals("Finalizer") || name.equals("Common-Cleaner")) |
1142 |
+ |
&& (lockName = info.getLockName()) != null |
1143 |
+ |
&& lockName.startsWith("java.lang.ref")) |
1144 |
+ |
return false; |
1145 |
+ |
if (name.startsWith("ForkJoinPool.commonPool-worker") |
1146 |
+ |
&& (lockName = info.getLockName()) != null |
1147 |
+ |
&& lockName.startsWith("java.util.concurrent.ForkJoinPool")) |
1148 |
+ |
return false; |
1149 |
+ |
return true; |
1150 |
+ |
} |
1151 |
+ |
|
1152 |
|
/** |
1153 |
|
* A debugging tool to print stack traces of most threads, as jstack does. |
1154 |
|
* Uninteresting threads are filtered out. |
1155 |
|
*/ |
1156 |
+ |
@SuppressWarnings("removal") |
1157 |
|
static void dumpTestThreads() { |
1158 |
< |
ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); |
1159 |
< |
System.err.println("------ stacktrace dump start ------"); |
1160 |
< |
for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) { |
1161 |
< |
String name = info.getThreadName(); |
1162 |
< |
if ("Signal Dispatcher".equals(name)) |
1163 |
< |
continue; |
1164 |
< |
if ("Reference Handler".equals(name) |
929 |
< |
&& info.getLockName().startsWith("java.lang.ref.Reference$Lock")) |
930 |
< |
continue; |
931 |
< |
if ("Finalizer".equals(name) |
932 |
< |
&& info.getLockName().startsWith("java.lang.ref.ReferenceQueue$Lock")) |
933 |
< |
continue; |
934 |
< |
if ("checkForWedgedTest".equals(name)) |
935 |
< |
continue; |
936 |
< |
System.err.print(info); |
1158 |
> |
SecurityManager sm = System.getSecurityManager(); |
1159 |
> |
if (sm != null) { |
1160 |
> |
try { |
1161 |
> |
System.setSecurityManager(null); |
1162 |
> |
} catch (SecurityException giveUp) { |
1163 |
> |
return; |
1164 |
> |
} |
1165 |
|
} |
1166 |
+ |
|
1167 |
+ |
System.err.println("------ stacktrace dump start ------"); |
1168 |
+ |
for (ThreadInfo info : THREAD_MXBEAN.dumpAllThreads(true, true)) |
1169 |
+ |
if (threadOfInterest(info)) |
1170 |
+ |
System.err.print(info); |
1171 |
|
System.err.println("------ stacktrace dump end ------"); |
939 |
– |
} |
1172 |
|
|
1173 |
< |
/** |
942 |
< |
* Checks that thread does not terminate within the default |
943 |
< |
* millisecond delay of {@code timeoutMillis()}. |
944 |
< |
*/ |
945 |
< |
void assertThreadStaysAlive(Thread thread) { |
946 |
< |
assertThreadStaysAlive(thread, timeoutMillis()); |
1173 |
> |
if (sm != null) System.setSecurityManager(sm); |
1174 |
|
} |
1175 |
|
|
1176 |
|
/** |
1177 |
< |
* Checks that thread does not terminate within the given millisecond delay. |
1177 |
> |
* Checks that thread eventually enters the expected blocked thread state. |
1178 |
|
*/ |
1179 |
< |
void assertThreadStaysAlive(Thread thread, long millis) { |
1180 |
< |
try { |
1181 |
< |
// No need to optimize the failing case via Thread.join. |
1182 |
< |
delay(millis); |
1183 |
< |
assertTrue(thread.isAlive()); |
1184 |
< |
} catch (InterruptedException fail) { |
1185 |
< |
threadFail("Unexpected InterruptedException"); |
1179 |
> |
void assertThreadBlocks(Thread thread, Thread.State expected) { |
1180 |
> |
// always sleep at least 1 ms, with high probability avoiding |
1181 |
> |
// transitory states |
1182 |
> |
for (long retries = LONG_DELAY_MS * 3 / 4; retries-->0; ) { |
1183 |
> |
try { delay(1); } |
1184 |
> |
catch (InterruptedException fail) { |
1185 |
> |
throw new AssertionError("Unexpected InterruptedException", fail); |
1186 |
> |
} |
1187 |
> |
Thread.State s = thread.getState(); |
1188 |
> |
if (s == expected) |
1189 |
> |
return; |
1190 |
> |
else if (s == Thread.State.TERMINATED) |
1191 |
> |
fail("Unexpected thread termination"); |
1192 |
|
} |
1193 |
+ |
fail("timed out waiting for thread to enter thread state " + expected); |
1194 |
|
} |
1195 |
|
|
1196 |
|
/** |
1197 |
< |
* Checks that the threads do not terminate within the default |
964 |
< |
* millisecond delay of {@code timeoutMillis()}. |
1197 |
> |
* Returns the thread's blocker's class name, if any, else null. |
1198 |
|
*/ |
1199 |
< |
void assertThreadsStayAlive(Thread... threads) { |
1200 |
< |
assertThreadsStayAlive(timeoutMillis(), threads); |
1201 |
< |
} |
1202 |
< |
|
1203 |
< |
/** |
1204 |
< |
* Checks that the threads do not terminate within the given millisecond delay. |
972 |
< |
*/ |
973 |
< |
void assertThreadsStayAlive(long millis, Thread... threads) { |
974 |
< |
try { |
975 |
< |
// No need to optimize the failing case via Thread.join. |
976 |
< |
delay(millis); |
977 |
< |
for (Thread thread : threads) |
978 |
< |
assertTrue(thread.isAlive()); |
979 |
< |
} catch (InterruptedException fail) { |
980 |
< |
threadFail("Unexpected InterruptedException"); |
981 |
< |
} |
1199 |
> |
String blockerClassName(Thread thread) { |
1200 |
> |
ThreadInfo threadInfo; LockInfo lockInfo; |
1201 |
> |
if ((threadInfo = THREAD_MXBEAN.getThreadInfo(thread.getId(), 0)) != null |
1202 |
> |
&& (lockInfo = threadInfo.getLockInfo()) != null) |
1203 |
> |
return lockInfo.getClassName(); |
1204 |
> |
return null; |
1205 |
|
} |
1206 |
|
|
1207 |
|
/** |
1208 |
|
* Checks that future.get times out, with the default timeout of |
1209 |
|
* {@code timeoutMillis()}. |
1210 |
|
*/ |
1211 |
< |
void assertFutureTimesOut(Future future) { |
1211 |
> |
void assertFutureTimesOut(Future<?> future) { |
1212 |
|
assertFutureTimesOut(future, timeoutMillis()); |
1213 |
|
} |
1214 |
|
|
1215 |
|
/** |
1216 |
|
* Checks that future.get times out, with the given millisecond timeout. |
1217 |
|
*/ |
1218 |
< |
void assertFutureTimesOut(Future future, long timeoutMillis) { |
1218 |
> |
void assertFutureTimesOut(Future<?> future, long timeoutMillis) { |
1219 |
|
long startTime = System.nanoTime(); |
1220 |
|
try { |
1221 |
|
future.get(timeoutMillis, MILLISECONDS); |
1223 |
|
} catch (TimeoutException success) { |
1224 |
|
} catch (Exception fail) { |
1225 |
|
threadUnexpectedException(fail); |
1226 |
< |
} finally { future.cancel(true); } |
1226 |
> |
} |
1227 |
|
assertTrue(millisElapsedSince(startTime) >= timeoutMillis); |
1228 |
+ |
assertFalse(future.isDone()); |
1229 |
|
} |
1230 |
|
|
1231 |
|
/** |
1243 |
|
} |
1244 |
|
|
1245 |
|
/** |
1246 |
< |
* The number of elements to place in collections, arrays, etc. |
1246 |
> |
* The maximum number of consecutive spurious wakeups we should |
1247 |
> |
* tolerate (from APIs like LockSupport.park) before failing a test. |
1248 |
|
*/ |
1249 |
< |
public static final int SIZE = 20; |
1249 |
> |
static final int MAX_SPURIOUS_WAKEUPS = 10; |
1250 |
|
|
1251 |
< |
// Some convenient Integer constants |
1251 |
> |
/** |
1252 |
> |
* The number of elements to place in collections, arrays, etc. |
1253 |
> |
* Must be at least ten; |
1254 |
> |
*/ |
1255 |
> |
public static final int SIZE = 32; |
1256 |
|
|
1257 |
< |
public static final Integer zero = new Integer(0); |
1258 |
< |
public static final Integer one = new Integer(1); |
1259 |
< |
public static final Integer two = new Integer(2); |
1260 |
< |
public static final Integer three = new Integer(3); |
1261 |
< |
public static final Integer four = new Integer(4); |
1262 |
< |
public static final Integer five = new Integer(5); |
1263 |
< |
public static final Integer six = new Integer(6); |
1264 |
< |
public static final Integer seven = new Integer(7); |
1265 |
< |
public static final Integer eight = new Integer(8); |
1266 |
< |
public static final Integer nine = new Integer(9); |
1267 |
< |
public static final Integer m1 = new Integer(-1); |
1268 |
< |
public static final Integer m2 = new Integer(-2); |
1269 |
< |
public static final Integer m3 = new Integer(-3); |
1270 |
< |
public static final Integer m4 = new Integer(-4); |
1271 |
< |
public static final Integer m5 = new Integer(-5); |
1272 |
< |
public static final Integer m6 = new Integer(-6); |
1273 |
< |
public static final Integer m10 = new Integer(-10); |
1257 |
> |
static Item[] seqItems(int size) { |
1258 |
> |
Item[] s = new Item[size]; |
1259 |
> |
for (int i = 0; i < size; ++i) |
1260 |
> |
s[i] = new Item(i); |
1261 |
> |
return s; |
1262 |
> |
} |
1263 |
> |
static Item[] negativeSeqItems(int size) { |
1264 |
> |
Item[] s = new Item[size]; |
1265 |
> |
for (int i = 0; i < size; ++i) |
1266 |
> |
s[i] = new Item(-i); |
1267 |
> |
return s; |
1268 |
> |
} |
1269 |
> |
|
1270 |
> |
// Many tests rely on defaultItems all being sequential nonnegative |
1271 |
> |
public static final Item[] defaultItems = seqItems(SIZE); |
1272 |
> |
|
1273 |
> |
static Item itemFor(int i) { // check cache for defaultItems |
1274 |
> |
Item[] items = defaultItems; |
1275 |
> |
return (i >= 0 && i < items.length) ? items[i] : new Item(i); |
1276 |
> |
} |
1277 |
> |
|
1278 |
> |
public static final Item zero = defaultItems[0]; |
1279 |
> |
public static final Item one = defaultItems[1]; |
1280 |
> |
public static final Item two = defaultItems[2]; |
1281 |
> |
public static final Item three = defaultItems[3]; |
1282 |
> |
public static final Item four = defaultItems[4]; |
1283 |
> |
public static final Item five = defaultItems[5]; |
1284 |
> |
public static final Item six = defaultItems[6]; |
1285 |
> |
public static final Item seven = defaultItems[7]; |
1286 |
> |
public static final Item eight = defaultItems[8]; |
1287 |
> |
public static final Item nine = defaultItems[9]; |
1288 |
> |
public static final Item ten = defaultItems[10]; |
1289 |
> |
|
1290 |
> |
public static final Item[] negativeItems = negativeSeqItems(SIZE); |
1291 |
> |
|
1292 |
> |
public static final Item minusOne = negativeItems[1]; |
1293 |
> |
public static final Item minusTwo = negativeItems[2]; |
1294 |
> |
public static final Item minusThree = negativeItems[3]; |
1295 |
> |
public static final Item minusFour = negativeItems[4]; |
1296 |
> |
public static final Item minusFive = negativeItems[5]; |
1297 |
> |
public static final Item minusSix = negativeItems[6]; |
1298 |
> |
public static final Item minusSeven = negativeItems[7]; |
1299 |
> |
public static final Item minusEight = negativeItems[8]; |
1300 |
> |
public static final Item minusNone = negativeItems[9]; |
1301 |
> |
public static final Item minusTen = negativeItems[10]; |
1302 |
> |
|
1303 |
> |
// elements expected to be missing |
1304 |
> |
public static final Item fortytwo = new Item(42); |
1305 |
> |
public static final Item eightysix = new Item(86); |
1306 |
> |
public static final Item ninetynine = new Item(99); |
1307 |
> |
|
1308 |
> |
// Interop across Item, int |
1309 |
> |
|
1310 |
> |
static void mustEqual(Item x, Item y) { |
1311 |
> |
if (x != y) |
1312 |
> |
assertEquals(x.value, y.value); |
1313 |
> |
} |
1314 |
> |
static void mustEqual(Item x, int y) { |
1315 |
> |
assertEquals(x.value, y); |
1316 |
> |
} |
1317 |
> |
static void mustEqual(int x, Item y) { |
1318 |
> |
assertEquals(x, y.value); |
1319 |
> |
} |
1320 |
> |
static void mustEqual(int x, int y) { |
1321 |
> |
assertEquals(x, y); |
1322 |
> |
} |
1323 |
> |
static void mustEqual(Object x, Object y) { |
1324 |
> |
if (x != y) |
1325 |
> |
assertEquals(x, y); |
1326 |
> |
} |
1327 |
> |
static void mustEqual(int x, Object y) { |
1328 |
> |
if (y instanceof Item) |
1329 |
> |
assertEquals(x, ((Item)y).value); |
1330 |
> |
else fail(); |
1331 |
> |
} |
1332 |
> |
static void mustEqual(Object x, int y) { |
1333 |
> |
if (x instanceof Item) |
1334 |
> |
assertEquals(((Item)x).value, y); |
1335 |
> |
else fail(); |
1336 |
> |
} |
1337 |
> |
static void mustEqual(boolean x, boolean y) { |
1338 |
> |
assertEquals(x, y); |
1339 |
> |
} |
1340 |
> |
static void mustEqual(long x, long y) { |
1341 |
> |
assertEquals(x, y); |
1342 |
> |
} |
1343 |
> |
static void mustEqual(double x, double y) { |
1344 |
> |
assertEquals(x, y); |
1345 |
> |
} |
1346 |
> |
static void mustContain(Collection<Item> c, int i) { |
1347 |
> |
assertTrue(c.contains(itemFor(i))); |
1348 |
> |
} |
1349 |
> |
static void mustContain(Collection<Item> c, Item i) { |
1350 |
> |
assertTrue(c.contains(i)); |
1351 |
> |
} |
1352 |
> |
static void mustNotContain(Collection<Item> c, int i) { |
1353 |
> |
assertFalse(c.contains(itemFor(i))); |
1354 |
> |
} |
1355 |
> |
static void mustNotContain(Collection<Item> c, Item i) { |
1356 |
> |
assertFalse(c.contains(i)); |
1357 |
> |
} |
1358 |
> |
static void mustRemove(Collection<Item> c, int i) { |
1359 |
> |
assertTrue(c.remove(itemFor(i))); |
1360 |
> |
} |
1361 |
> |
static void mustRemove(Collection<Item> c, Item i) { |
1362 |
> |
assertTrue(c.remove(i)); |
1363 |
> |
} |
1364 |
> |
static void mustNotRemove(Collection<Item> c, int i) { |
1365 |
> |
assertFalse(c.remove(itemFor(i))); |
1366 |
> |
} |
1367 |
> |
static void mustNotRemove(Collection<Item> c, Item i) { |
1368 |
> |
assertFalse(c.remove(i)); |
1369 |
> |
} |
1370 |
> |
static void mustAdd(Collection<Item> c, int i) { |
1371 |
> |
assertTrue(c.add(itemFor(i))); |
1372 |
> |
} |
1373 |
> |
static void mustAdd(Collection<Item> c, Item i) { |
1374 |
> |
assertTrue(c.add(i)); |
1375 |
> |
} |
1376 |
> |
static void mustOffer(Queue<Item> c, int i) { |
1377 |
> |
assertTrue(c.offer(itemFor(i))); |
1378 |
> |
} |
1379 |
> |
static void mustOffer(Queue<Item> c, Item i) { |
1380 |
> |
assertTrue(c.offer(i)); |
1381 |
> |
} |
1382 |
|
|
1383 |
|
/** |
1384 |
|
* Runs Runnable r with a security policy that permits precisely |
1387 |
|
* security manager. We require that any security manager permit |
1388 |
|
* getPolicy/setPolicy. |
1389 |
|
*/ |
1390 |
+ |
@SuppressWarnings("removal") |
1391 |
|
public void runWithPermissions(Runnable r, Permission... permissions) { |
1392 |
|
SecurityManager sm = System.getSecurityManager(); |
1393 |
|
if (sm == null) { |
1403 |
|
* Runnable. We require that any security manager permit |
1404 |
|
* getPolicy/setPolicy. |
1405 |
|
*/ |
1406 |
+ |
@SuppressWarnings("removal") |
1407 |
|
public void runWithSecurityManagerWithPermissions(Runnable r, |
1408 |
|
Permission... permissions) { |
1409 |
+ |
if (!useSecurityManager) return; |
1410 |
|
SecurityManager sm = System.getSecurityManager(); |
1411 |
|
if (sm == null) { |
1412 |
|
Policy savedPolicy = Policy.getPolicy(); |
1414 |
|
Policy.setPolicy(permissivePolicy()); |
1415 |
|
System.setSecurityManager(new SecurityManager()); |
1416 |
|
runWithSecurityManagerWithPermissions(r, permissions); |
1417 |
+ |
} catch (UnsupportedOperationException ok) { |
1418 |
|
} finally { |
1419 |
< |
System.setSecurityManager(null); |
1420 |
< |
Policy.setPolicy(savedPolicy); |
1419 |
> |
try { |
1420 |
> |
System.setSecurityManager(null); |
1421 |
> |
Policy.setPolicy(savedPolicy); |
1422 |
> |
} catch (Exception ok) { |
1423 |
> |
} |
1424 |
|
} |
1425 |
|
} else { |
1426 |
|
Policy savedPolicy = Policy.getPolicy(); |
1447 |
|
* A security policy where new permissions can be dynamically added |
1448 |
|
* or all cleared. |
1449 |
|
*/ |
1450 |
+ |
@SuppressWarnings("removal") |
1451 |
|
public static class AdjustablePolicy extends java.security.Policy { |
1452 |
|
Permissions perms = new Permissions(); |
1453 |
|
AdjustablePolicy(Permission... permissions) { |
1467 |
|
} |
1468 |
|
public void refresh() {} |
1469 |
|
public String toString() { |
1470 |
< |
List<Permission> ps = new ArrayList<Permission>(); |
1470 |
> |
List<Permission> ps = new ArrayList<>(); |
1471 |
|
for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();) |
1472 |
|
ps.add(e.nextElement()); |
1473 |
|
return "AdjustablePolicy with permissions " + ps; |
1477 |
|
/** |
1478 |
|
* Returns a policy containing all the permissions we ever need. |
1479 |
|
*/ |
1480 |
+ |
@SuppressWarnings("removal") |
1481 |
|
public static Policy permissivePolicy() { |
1482 |
|
return new AdjustablePolicy |
1483 |
|
// Permissions j.u.c. needs directly |
1496 |
|
|
1497 |
|
/** |
1498 |
|
* Sleeps until the given time has elapsed. |
1499 |
< |
* Throws AssertionFailedError if interrupted. |
1499 |
> |
* Throws AssertionError if interrupted. |
1500 |
|
*/ |
1501 |
< |
void sleep(long millis) { |
1501 |
> |
static void sleep(long millis) { |
1502 |
|
try { |
1503 |
|
delay(millis); |
1504 |
|
} catch (InterruptedException fail) { |
1505 |
< |
AssertionFailedError afe = |
1160 |
< |
new AssertionFailedError("Unexpected InterruptedException"); |
1161 |
< |
afe.initCause(fail); |
1162 |
< |
throw afe; |
1505 |
> |
throw new AssertionError("Unexpected InterruptedException", fail); |
1506 |
|
} |
1507 |
|
} |
1508 |
|
|
1509 |
|
/** |
1510 |
|
* Spin-waits up to the specified number of milliseconds for the given |
1511 |
|
* thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING. |
1512 |
+ |
* @param waitingForGodot if non-null, an additional condition to satisfy |
1513 |
|
*/ |
1514 |
< |
void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) { |
1515 |
< |
long startTime = System.nanoTime(); |
1516 |
< |
for (;;) { |
1517 |
< |
Thread.State s = thread.getState(); |
1518 |
< |
if (s == Thread.State.BLOCKED || |
1519 |
< |
s == Thread.State.WAITING || |
1520 |
< |
s == Thread.State.TIMED_WAITING) |
1521 |
< |
return; |
1522 |
< |
else if (s == Thread.State.TERMINATED) |
1514 |
> |
void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis, |
1515 |
> |
Callable<Boolean> waitingForGodot) { |
1516 |
> |
for (long startTime = 0L;;) { |
1517 |
> |
switch (thread.getState()) { |
1518 |
> |
default: break; |
1519 |
> |
case BLOCKED: case WAITING: case TIMED_WAITING: |
1520 |
> |
try { |
1521 |
> |
if (waitingForGodot == null || waitingForGodot.call()) |
1522 |
> |
return; |
1523 |
> |
} catch (Throwable fail) { threadUnexpectedException(fail); } |
1524 |
> |
break; |
1525 |
> |
case TERMINATED: |
1526 |
|
fail("Unexpected thread termination"); |
1527 |
+ |
} |
1528 |
+ |
|
1529 |
+ |
if (startTime == 0L) |
1530 |
+ |
startTime = System.nanoTime(); |
1531 |
|
else if (millisElapsedSince(startTime) > timeoutMillis) { |
1532 |
< |
threadAssertTrue(thread.isAlive()); |
1533 |
< |
return; |
1532 |
> |
assertTrue(thread.isAlive()); |
1533 |
> |
if (waitingForGodot == null |
1534 |
> |
|| thread.getState() == Thread.State.RUNNABLE) |
1535 |
> |
fail("timed out waiting for thread to enter wait state"); |
1536 |
> |
else |
1537 |
> |
fail("timed out waiting for condition, thread state=" |
1538 |
> |
+ thread.getState()); |
1539 |
|
} |
1540 |
|
Thread.yield(); |
1541 |
|
} |
1542 |
|
} |
1543 |
|
|
1544 |
|
/** |
1545 |
< |
* Waits up to LONG_DELAY_MS for the given thread to enter a wait |
1546 |
< |
* state: BLOCKED, WAITING, or TIMED_WAITING. |
1545 |
> |
* Spin-waits up to the specified number of milliseconds for the given |
1546 |
> |
* thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING. |
1547 |
> |
*/ |
1548 |
> |
void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) { |
1549 |
> |
waitForThreadToEnterWaitState(thread, timeoutMillis, null); |
1550 |
> |
} |
1551 |
> |
|
1552 |
> |
/** |
1553 |
> |
* Spin-waits up to LONG_DELAY_MS milliseconds for the given thread to |
1554 |
> |
* enter a wait state: BLOCKED, WAITING, or TIMED_WAITING. |
1555 |
|
*/ |
1556 |
|
void waitForThreadToEnterWaitState(Thread thread) { |
1557 |
< |
waitForThreadToEnterWaitState(thread, LONG_DELAY_MS); |
1557 |
> |
waitForThreadToEnterWaitState(thread, LONG_DELAY_MS, null); |
1558 |
> |
} |
1559 |
> |
|
1560 |
> |
/** |
1561 |
> |
* Spin-waits up to LONG_DELAY_MS milliseconds for the given thread to |
1562 |
> |
* enter a wait state: BLOCKED, WAITING, or TIMED_WAITING, |
1563 |
> |
* and additionally satisfy the given condition. |
1564 |
> |
*/ |
1565 |
> |
void waitForThreadToEnterWaitState(Thread thread, |
1566 |
> |
Callable<Boolean> waitingForGodot) { |
1567 |
> |
waitForThreadToEnterWaitState(thread, LONG_DELAY_MS, waitingForGodot); |
1568 |
> |
} |
1569 |
> |
|
1570 |
> |
/** |
1571 |
> |
* Spin-waits up to LONG_DELAY_MS milliseconds for the current thread to |
1572 |
> |
* be interrupted. Clears the interrupt status before returning. |
1573 |
> |
*/ |
1574 |
> |
void awaitInterrupted() { |
1575 |
> |
for (long startTime = 0L; !Thread.interrupted(); ) { |
1576 |
> |
if (startTime == 0L) |
1577 |
> |
startTime = System.nanoTime(); |
1578 |
> |
else if (millisElapsedSince(startTime) > LONG_DELAY_MS) |
1579 |
> |
fail("timed out waiting for thread interrupt"); |
1580 |
> |
Thread.yield(); |
1581 |
> |
} |
1582 |
|
} |
1583 |
|
|
1584 |
|
/** |
1590 |
|
return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime); |
1591 |
|
} |
1592 |
|
|
1205 |
– |
// void assertTerminatesPromptly(long timeoutMillis, Runnable r) { |
1206 |
– |
// long startTime = System.nanoTime(); |
1207 |
– |
// try { |
1208 |
– |
// r.run(); |
1209 |
– |
// } catch (Throwable fail) { threadUnexpectedException(fail); } |
1210 |
– |
// if (millisElapsedSince(startTime) > timeoutMillis/2) |
1211 |
– |
// throw new AssertionFailedError("did not return promptly"); |
1212 |
– |
// } |
1213 |
– |
|
1214 |
– |
// void assertTerminatesPromptly(Runnable r) { |
1215 |
– |
// assertTerminatesPromptly(LONG_DELAY_MS/2, r); |
1216 |
– |
// } |
1217 |
– |
|
1593 |
|
/** |
1594 |
|
* Checks that timed f.get() returns the expected value, and does not |
1595 |
|
* wait for the timeout to elapse before returning. |
1596 |
|
*/ |
1597 |
|
<T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) { |
1598 |
|
long startTime = System.nanoTime(); |
1599 |
+ |
T actual = null; |
1600 |
|
try { |
1601 |
< |
assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS)); |
1601 |
> |
actual = f.get(timeoutMillis, MILLISECONDS); |
1602 |
|
} catch (Throwable fail) { threadUnexpectedException(fail); } |
1603 |
+ |
assertEquals(expectedValue, actual); |
1604 |
|
if (millisElapsedSince(startTime) > timeoutMillis/2) |
1605 |
< |
throw new AssertionFailedError("timed get did not return promptly"); |
1605 |
> |
throw new AssertionError("timed get did not return promptly"); |
1606 |
|
} |
1607 |
|
|
1608 |
|
<T> void checkTimedGet(Future<T> f, T expectedValue) { |
1620 |
|
} |
1621 |
|
|
1622 |
|
/** |
1623 |
+ |
* Returns a new started daemon Thread running the given action, |
1624 |
+ |
* wrapped in a CheckedRunnable. |
1625 |
+ |
*/ |
1626 |
+ |
Thread newStartedThread(Action action) { |
1627 |
+ |
return newStartedThread(checkedRunnable(action)); |
1628 |
+ |
} |
1629 |
+ |
|
1630 |
+ |
/** |
1631 |
|
* Waits for the specified time (in milliseconds) for the thread |
1632 |
|
* to terminate (using {@link Thread#join(long)}), else interrupts |
1633 |
|
* the thread (in the hope that it may terminate later) and fails. |
1634 |
|
*/ |
1635 |
< |
void awaitTermination(Thread t, long timeoutMillis) { |
1635 |
> |
void awaitTermination(Thread thread, long timeoutMillis) { |
1636 |
|
try { |
1637 |
< |
t.join(timeoutMillis); |
1637 |
> |
thread.join(timeoutMillis); |
1638 |
|
} catch (InterruptedException fail) { |
1639 |
|
threadUnexpectedException(fail); |
1640 |
< |
} finally { |
1641 |
< |
if (t.getState() != Thread.State.TERMINATED) { |
1642 |
< |
t.interrupt(); |
1643 |
< |
threadFail("timed out waiting for thread to terminate"); |
1640 |
> |
} |
1641 |
> |
if (thread.getState() != Thread.State.TERMINATED) { |
1642 |
> |
String detail = String.format( |
1643 |
> |
"timed out waiting for thread to terminate, thread=%s, state=%s" , |
1644 |
> |
thread, thread.getState()); |
1645 |
> |
try { |
1646 |
> |
threadFail(detail); |
1647 |
> |
} finally { |
1648 |
> |
// Interrupt thread __after__ having reported its stack trace |
1649 |
> |
thread.interrupt(); |
1650 |
|
} |
1651 |
|
} |
1652 |
|
} |
1674 |
|
} |
1675 |
|
} |
1676 |
|
|
1677 |
< |
public abstract class RunnableShouldThrow implements Runnable { |
1678 |
< |
protected abstract void realRun() throws Throwable; |
1679 |
< |
|
1680 |
< |
final Class<?> exceptionClass; |
1681 |
< |
|
1291 |
< |
<T extends Throwable> RunnableShouldThrow(Class<T> exceptionClass) { |
1292 |
< |
this.exceptionClass = exceptionClass; |
1293 |
< |
} |
1294 |
< |
|
1295 |
< |
public final void run() { |
1296 |
< |
try { |
1297 |
< |
realRun(); |
1298 |
< |
threadShouldThrow(exceptionClass.getSimpleName()); |
1299 |
< |
} catch (Throwable t) { |
1300 |
< |
if (! exceptionClass.isInstance(t)) |
1301 |
< |
threadUnexpectedException(t); |
1302 |
< |
} |
1303 |
< |
} |
1677 |
> |
Runnable checkedRunnable(Action action) { |
1678 |
> |
return new CheckedRunnable() { |
1679 |
> |
public void realRun() throws Throwable { |
1680 |
> |
action.run(); |
1681 |
> |
}}; |
1682 |
|
} |
1683 |
|
|
1684 |
|
public abstract class ThreadShouldThrow extends Thread { |
1693 |
|
public final void run() { |
1694 |
|
try { |
1695 |
|
realRun(); |
1318 |
– |
threadShouldThrow(exceptionClass.getSimpleName()); |
1696 |
|
} catch (Throwable t) { |
1697 |
|
if (! exceptionClass.isInstance(t)) |
1698 |
|
threadUnexpectedException(t); |
1699 |
+ |
return; |
1700 |
|
} |
1701 |
+ |
threadShouldThrow(exceptionClass.getSimpleName()); |
1702 |
|
} |
1703 |
|
} |
1704 |
|
|
1708 |
|
public final void run() { |
1709 |
|
try { |
1710 |
|
realRun(); |
1332 |
– |
threadShouldThrow("InterruptedException"); |
1711 |
|
} catch (InterruptedException success) { |
1712 |
|
threadAssertFalse(Thread.interrupted()); |
1713 |
+ |
return; |
1714 |
|
} catch (Throwable fail) { |
1715 |
|
threadUnexpectedException(fail); |
1716 |
|
} |
1717 |
+ |
threadShouldThrow("InterruptedException"); |
1718 |
|
} |
1719 |
|
} |
1720 |
|
|
1726 |
|
return realCall(); |
1727 |
|
} catch (Throwable fail) { |
1728 |
|
threadUnexpectedException(fail); |
1349 |
– |
return null; |
1350 |
– |
} |
1351 |
– |
} |
1352 |
– |
} |
1353 |
– |
|
1354 |
– |
public abstract class CheckedInterruptedCallable<T> |
1355 |
– |
implements Callable<T> { |
1356 |
– |
protected abstract T realCall() throws Throwable; |
1357 |
– |
|
1358 |
– |
public final T call() { |
1359 |
– |
try { |
1360 |
– |
T result = realCall(); |
1361 |
– |
threadShouldThrow("InterruptedException"); |
1362 |
– |
return result; |
1363 |
– |
} catch (InterruptedException success) { |
1364 |
– |
threadAssertFalse(Thread.interrupted()); |
1365 |
– |
} catch (Throwable fail) { |
1366 |
– |
threadUnexpectedException(fail); |
1729 |
|
} |
1730 |
< |
return null; |
1730 |
> |
throw new AssertionError("unreached"); |
1731 |
|
} |
1732 |
|
} |
1733 |
|
|
1735 |
|
public void run() {} |
1736 |
|
} |
1737 |
|
|
1738 |
< |
public static class NoOpCallable implements Callable { |
1738 |
> |
public static class NoOpCallable implements Callable<Object> { |
1739 |
|
public Object call() { return Boolean.TRUE; } |
1740 |
|
} |
1741 |
|
|
1783 |
|
return new LatchAwaiter(latch); |
1784 |
|
} |
1785 |
|
|
1786 |
< |
public void await(CountDownLatch latch) { |
1786 |
> |
public void await(CountDownLatch latch, long timeoutMillis) { |
1787 |
> |
boolean timedOut = false; |
1788 |
|
try { |
1789 |
< |
if (!latch.await(LONG_DELAY_MS, MILLISECONDS)) |
1427 |
< |
fail("timed out waiting for CountDownLatch for " |
1428 |
< |
+ (LONG_DELAY_MS/1000) + " sec"); |
1789 |
> |
timedOut = !latch.await(timeoutMillis, MILLISECONDS); |
1790 |
|
} catch (Throwable fail) { |
1791 |
|
threadUnexpectedException(fail); |
1792 |
|
} |
1793 |
+ |
if (timedOut) |
1794 |
+ |
fail("timed out waiting for CountDownLatch for " |
1795 |
+ |
+ (timeoutMillis/1000) + " sec"); |
1796 |
+ |
} |
1797 |
+ |
|
1798 |
+ |
public void await(CountDownLatch latch) { |
1799 |
+ |
await(latch, LONG_DELAY_MS); |
1800 |
|
} |
1801 |
|
|
1802 |
|
public void await(Semaphore semaphore) { |
1803 |
+ |
boolean timedOut = false; |
1804 |
+ |
try { |
1805 |
+ |
timedOut = !semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS); |
1806 |
+ |
} catch (Throwable fail) { |
1807 |
+ |
threadUnexpectedException(fail); |
1808 |
+ |
} |
1809 |
+ |
if (timedOut) |
1810 |
+ |
fail("timed out waiting for Semaphore for " |
1811 |
+ |
+ (LONG_DELAY_MS/1000) + " sec"); |
1812 |
+ |
} |
1813 |
+ |
|
1814 |
+ |
public void await(CyclicBarrier barrier) { |
1815 |
|
try { |
1816 |
< |
if (!semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS)) |
1437 |
< |
fail("timed out waiting for Semaphore for " |
1438 |
< |
+ (LONG_DELAY_MS/1000) + " sec"); |
1816 |
> |
barrier.await(LONG_DELAY_MS, MILLISECONDS); |
1817 |
|
} catch (Throwable fail) { |
1818 |
|
threadUnexpectedException(fail); |
1819 |
|
} |
1833 |
|
// long startTime = System.nanoTime(); |
1834 |
|
// while (!flag.get()) { |
1835 |
|
// if (millisElapsedSince(startTime) > timeoutMillis) |
1836 |
< |
// throw new AssertionFailedError("timed out"); |
1836 |
> |
// throw new AssertionError("timed out"); |
1837 |
|
// Thread.yield(); |
1838 |
|
// } |
1839 |
|
// } |
1842 |
|
public String call() { throw new NullPointerException(); } |
1843 |
|
} |
1844 |
|
|
1467 |
– |
public static class CallableOne implements Callable<Integer> { |
1468 |
– |
public Integer call() { return one; } |
1469 |
– |
} |
1470 |
– |
|
1471 |
– |
public class ShortRunnable extends CheckedRunnable { |
1472 |
– |
protected void realRun() throws Throwable { |
1473 |
– |
delay(SHORT_DELAY_MS); |
1474 |
– |
} |
1475 |
– |
} |
1476 |
– |
|
1477 |
– |
public class ShortInterruptedRunnable extends CheckedInterruptedRunnable { |
1478 |
– |
protected void realRun() throws InterruptedException { |
1479 |
– |
delay(SHORT_DELAY_MS); |
1480 |
– |
} |
1481 |
– |
} |
1482 |
– |
|
1483 |
– |
public class SmallRunnable extends CheckedRunnable { |
1484 |
– |
protected void realRun() throws Throwable { |
1485 |
– |
delay(SMALL_DELAY_MS); |
1486 |
– |
} |
1487 |
– |
} |
1488 |
– |
|
1489 |
– |
public class SmallPossiblyInterruptedRunnable extends CheckedRunnable { |
1490 |
– |
protected void realRun() { |
1491 |
– |
try { |
1492 |
– |
delay(SMALL_DELAY_MS); |
1493 |
– |
} catch (InterruptedException ok) {} |
1494 |
– |
} |
1495 |
– |
} |
1496 |
– |
|
1497 |
– |
public class SmallCallable extends CheckedCallable { |
1498 |
– |
protected Object realCall() throws InterruptedException { |
1499 |
– |
delay(SMALL_DELAY_MS); |
1500 |
– |
return Boolean.TRUE; |
1501 |
– |
} |
1502 |
– |
} |
1503 |
– |
|
1504 |
– |
public class MediumRunnable extends CheckedRunnable { |
1505 |
– |
protected void realRun() throws Throwable { |
1506 |
– |
delay(MEDIUM_DELAY_MS); |
1507 |
– |
} |
1508 |
– |
} |
1509 |
– |
|
1510 |
– |
public class MediumInterruptedRunnable extends CheckedInterruptedRunnable { |
1511 |
– |
protected void realRun() throws InterruptedException { |
1512 |
– |
delay(MEDIUM_DELAY_MS); |
1513 |
– |
} |
1514 |
– |
} |
1515 |
– |
|
1845 |
|
public Runnable possiblyInterruptedRunnable(final long timeoutMillis) { |
1846 |
|
return new CheckedRunnable() { |
1847 |
|
protected void realRun() { |
1851 |
|
}}; |
1852 |
|
} |
1853 |
|
|
1525 |
– |
public class MediumPossiblyInterruptedRunnable extends CheckedRunnable { |
1526 |
– |
protected void realRun() { |
1527 |
– |
try { |
1528 |
– |
delay(MEDIUM_DELAY_MS); |
1529 |
– |
} catch (InterruptedException ok) {} |
1530 |
– |
} |
1531 |
– |
} |
1532 |
– |
|
1533 |
– |
public class LongPossiblyInterruptedRunnable extends CheckedRunnable { |
1534 |
– |
protected void realRun() { |
1535 |
– |
try { |
1536 |
– |
delay(LONG_DELAY_MS); |
1537 |
– |
} catch (InterruptedException ok) {} |
1538 |
– |
} |
1539 |
– |
} |
1540 |
– |
|
1854 |
|
/** |
1855 |
|
* For use as ThreadFactory in constructors |
1856 |
|
*/ |
1864 |
|
boolean isDone(); |
1865 |
|
} |
1866 |
|
|
1554 |
– |
public static TrackedRunnable trackedRunnable(final long timeoutMillis) { |
1555 |
– |
return new TrackedRunnable() { |
1556 |
– |
private volatile boolean done = false; |
1557 |
– |
public boolean isDone() { return done; } |
1558 |
– |
public void run() { |
1559 |
– |
try { |
1560 |
– |
delay(timeoutMillis); |
1561 |
– |
done = true; |
1562 |
– |
} catch (InterruptedException ok) {} |
1563 |
– |
} |
1564 |
– |
}; |
1565 |
– |
} |
1566 |
– |
|
1567 |
– |
public static class TrackedShortRunnable implements Runnable { |
1568 |
– |
public volatile boolean done = false; |
1569 |
– |
public void run() { |
1570 |
– |
try { |
1571 |
– |
delay(SHORT_DELAY_MS); |
1572 |
– |
done = true; |
1573 |
– |
} catch (InterruptedException ok) {} |
1574 |
– |
} |
1575 |
– |
} |
1576 |
– |
|
1577 |
– |
public static class TrackedSmallRunnable implements Runnable { |
1578 |
– |
public volatile boolean done = false; |
1579 |
– |
public void run() { |
1580 |
– |
try { |
1581 |
– |
delay(SMALL_DELAY_MS); |
1582 |
– |
done = true; |
1583 |
– |
} catch (InterruptedException ok) {} |
1584 |
– |
} |
1585 |
– |
} |
1586 |
– |
|
1587 |
– |
public static class TrackedMediumRunnable implements Runnable { |
1588 |
– |
public volatile boolean done = false; |
1589 |
– |
public void run() { |
1590 |
– |
try { |
1591 |
– |
delay(MEDIUM_DELAY_MS); |
1592 |
– |
done = true; |
1593 |
– |
} catch (InterruptedException ok) {} |
1594 |
– |
} |
1595 |
– |
} |
1596 |
– |
|
1597 |
– |
public static class TrackedLongRunnable implements Runnable { |
1598 |
– |
public volatile boolean done = false; |
1599 |
– |
public void run() { |
1600 |
– |
try { |
1601 |
– |
delay(LONG_DELAY_MS); |
1602 |
– |
done = true; |
1603 |
– |
} catch (InterruptedException ok) {} |
1604 |
– |
} |
1605 |
– |
} |
1606 |
– |
|
1867 |
|
public static class TrackedNoOpRunnable implements Runnable { |
1868 |
|
public volatile boolean done = false; |
1869 |
|
public void run() { |
1871 |
|
} |
1872 |
|
} |
1873 |
|
|
1614 |
– |
public static class TrackedCallable implements Callable { |
1615 |
– |
public volatile boolean done = false; |
1616 |
– |
public Object call() { |
1617 |
– |
try { |
1618 |
– |
delay(SMALL_DELAY_MS); |
1619 |
– |
done = true; |
1620 |
– |
} catch (InterruptedException ok) {} |
1621 |
– |
return Boolean.TRUE; |
1622 |
– |
} |
1623 |
– |
} |
1624 |
– |
|
1874 |
|
/** |
1875 |
|
* Analog of CheckedRunnable for RecursiveAction |
1876 |
|
*/ |
1897 |
|
return realCompute(); |
1898 |
|
} catch (Throwable fail) { |
1899 |
|
threadUnexpectedException(fail); |
1651 |
– |
return null; |
1900 |
|
} |
1901 |
+ |
throw new AssertionError("unreached"); |
1902 |
|
} |
1903 |
|
} |
1904 |
|
|
1912 |
|
|
1913 |
|
/** |
1914 |
|
* A CyclicBarrier that uses timed await and fails with |
1915 |
< |
* AssertionFailedErrors instead of throwing checked exceptions. |
1915 |
> |
* AssertionErrors instead of throwing checked exceptions. |
1916 |
|
*/ |
1917 |
< |
public class CheckedBarrier extends CyclicBarrier { |
1917 |
> |
public static class CheckedBarrier extends CyclicBarrier { |
1918 |
|
public CheckedBarrier(int parties) { super(parties); } |
1919 |
|
|
1920 |
|
public int await() { |
1921 |
|
try { |
1922 |
< |
return super.await(2 * LONG_DELAY_MS, MILLISECONDS); |
1922 |
> |
return super.await(LONGER_DELAY_MS, MILLISECONDS); |
1923 |
|
} catch (TimeoutException timedOut) { |
1924 |
< |
throw new AssertionFailedError("timed out"); |
1924 |
> |
throw new AssertionError("timed out"); |
1925 |
|
} catch (Exception fail) { |
1926 |
< |
AssertionFailedError afe = |
1678 |
< |
new AssertionFailedError("Unexpected exception: " + fail); |
1679 |
< |
afe.initCause(fail); |
1680 |
< |
throw afe; |
1926 |
> |
throw new AssertionError("Unexpected exception: " + fail, fail); |
1927 |
|
} |
1928 |
|
} |
1929 |
|
} |
1930 |
|
|
1931 |
< |
void checkEmpty(BlockingQueue q) { |
1931 |
> |
void checkEmpty(BlockingQueue<?> q) { |
1932 |
|
try { |
1933 |
|
assertTrue(q.isEmpty()); |
1934 |
|
assertEquals(0, q.size()); |
1935 |
|
assertNull(q.peek()); |
1936 |
|
assertNull(q.poll()); |
1937 |
< |
assertNull(q.poll(0, MILLISECONDS)); |
1937 |
> |
assertNull(q.poll(randomExpiredTimeout(), randomTimeUnit())); |
1938 |
|
assertEquals(q.toString(), "[]"); |
1939 |
|
assertTrue(Arrays.equals(q.toArray(), new Object[0])); |
1940 |
|
assertFalse(q.iterator().hasNext()); |
1976 |
|
} |
1977 |
|
|
1978 |
|
@SuppressWarnings("unchecked") |
1979 |
+ |
void assertImmutable(Object o) { |
1980 |
+ |
if (o instanceof Collection) { |
1981 |
+ |
assertThrows( |
1982 |
+ |
UnsupportedOperationException.class, |
1983 |
+ |
() -> ((Collection) o).add(null)); |
1984 |
+ |
} |
1985 |
+ |
} |
1986 |
+ |
|
1987 |
+ |
@SuppressWarnings("unchecked") |
1988 |
|
<T> T serialClone(T o) { |
1989 |
+ |
T clone = null; |
1990 |
|
try { |
1991 |
|
ObjectInputStream ois = new ObjectInputStream |
1992 |
|
(new ByteArrayInputStream(serialBytes(o))); |
1993 |
< |
T clone = (T) ois.readObject(); |
1738 |
< |
assertSame(o.getClass(), clone.getClass()); |
1739 |
< |
return clone; |
1993 |
> |
clone = (T) ois.readObject(); |
1994 |
|
} catch (Throwable fail) { |
1995 |
|
threadUnexpectedException(fail); |
1996 |
+ |
} |
1997 |
+ |
if (o == clone) assertImmutable(o); |
1998 |
+ |
else assertSame(o.getClass(), clone.getClass()); |
1999 |
+ |
return clone; |
2000 |
+ |
} |
2001 |
+ |
|
2002 |
+ |
/** |
2003 |
+ |
* A version of serialClone that leaves error handling (for |
2004 |
+ |
* e.g. NotSerializableException) up to the caller. |
2005 |
+ |
*/ |
2006 |
+ |
@SuppressWarnings("unchecked") |
2007 |
+ |
<T> T serialClonePossiblyFailing(T o) |
2008 |
+ |
throws ReflectiveOperationException, java.io.IOException { |
2009 |
+ |
ByteArrayOutputStream bos = new ByteArrayOutputStream(); |
2010 |
+ |
ObjectOutputStream oos = new ObjectOutputStream(bos); |
2011 |
+ |
oos.writeObject(o); |
2012 |
+ |
oos.flush(); |
2013 |
+ |
oos.close(); |
2014 |
+ |
ObjectInputStream ois = new ObjectInputStream |
2015 |
+ |
(new ByteArrayInputStream(bos.toByteArray())); |
2016 |
+ |
T clone = (T) ois.readObject(); |
2017 |
+ |
if (o == clone) assertImmutable(o); |
2018 |
+ |
else assertSame(o.getClass(), clone.getClass()); |
2019 |
+ |
return clone; |
2020 |
+ |
} |
2021 |
+ |
|
2022 |
+ |
/** |
2023 |
+ |
* If o implements Cloneable and has a public clone method, |
2024 |
+ |
* returns a clone of o, else null. |
2025 |
+ |
*/ |
2026 |
+ |
@SuppressWarnings("unchecked") |
2027 |
+ |
<T> T cloneableClone(T o) { |
2028 |
+ |
if (!(o instanceof Cloneable)) return null; |
2029 |
+ |
final T clone; |
2030 |
+ |
try { |
2031 |
+ |
clone = (T) o.getClass().getMethod("clone").invoke(o); |
2032 |
+ |
} catch (NoSuchMethodException ok) { |
2033 |
|
return null; |
2034 |
+ |
} catch (ReflectiveOperationException unexpected) { |
2035 |
+ |
throw new Error(unexpected); |
2036 |
|
} |
2037 |
+ |
assertNotSame(o, clone); // not 100% guaranteed by spec |
2038 |
+ |
assertSame(o.getClass(), clone.getClass()); |
2039 |
+ |
return clone; |
2040 |
|
} |
2041 |
|
|
2042 |
|
public void assertThrows(Class<? extends Throwable> expectedExceptionClass, |
2043 |
< |
Runnable... throwingActions) { |
2044 |
< |
for (Runnable throwingAction : throwingActions) { |
2043 |
> |
Action... throwingActions) { |
2044 |
> |
for (Action throwingAction : throwingActions) { |
2045 |
|
boolean threw = false; |
2046 |
|
try { throwingAction.run(); } |
2047 |
|
catch (Throwable t) { |
2048 |
|
threw = true; |
2049 |
< |
if (!expectedExceptionClass.isInstance(t)) { |
2050 |
< |
AssertionFailedError afe = |
2051 |
< |
new AssertionFailedError |
2052 |
< |
("Expected " + expectedExceptionClass.getName() + |
2053 |
< |
", got " + t.getClass().getName()); |
1758 |
< |
afe.initCause(t); |
1759 |
< |
threadUnexpectedException(afe); |
1760 |
< |
} |
2049 |
> |
if (!expectedExceptionClass.isInstance(t)) |
2050 |
> |
throw new AssertionError( |
2051 |
> |
"Expected " + expectedExceptionClass.getName() + |
2052 |
> |
", got " + t.getClass().getName(), |
2053 |
> |
t); |
2054 |
|
} |
2055 |
|
if (!threw) |
2056 |
|
shouldThrow(expectedExceptionClass.getName()); |
2064 |
|
} catch (NoSuchElementException success) {} |
2065 |
|
assertFalse(it.hasNext()); |
2066 |
|
} |
2067 |
+ |
|
2068 |
+ |
public <T> Callable<T> callableThrowing(final Exception ex) { |
2069 |
+ |
return new Callable<T>() { public T call() throws Exception { throw ex; }}; |
2070 |
+ |
} |
2071 |
+ |
|
2072 |
+ |
public Runnable runnableThrowing(final RuntimeException ex) { |
2073 |
+ |
return new Runnable() { public void run() { throw ex; }}; |
2074 |
+ |
} |
2075 |
+ |
|
2076 |
+ |
/** A reusable thread pool to be shared by tests. */ |
2077 |
+ |
static final ExecutorService cachedThreadPool = |
2078 |
+ |
new ThreadPoolExecutor(0, Integer.MAX_VALUE, |
2079 |
+ |
1000L, MILLISECONDS, |
2080 |
+ |
new SynchronousQueue<Runnable>()); |
2081 |
+ |
|
2082 |
+ |
static <T> void shuffle(T[] array) { |
2083 |
+ |
Collections.shuffle(Arrays.asList(array), ThreadLocalRandom.current()); |
2084 |
+ |
} |
2085 |
+ |
|
2086 |
+ |
/** |
2087 |
+ |
* Returns the same String as would be returned by {@link |
2088 |
+ |
* Object#toString}, whether or not the given object's class |
2089 |
+ |
* overrides toString(). |
2090 |
+ |
* |
2091 |
+ |
* @see System#identityHashCode |
2092 |
+ |
*/ |
2093 |
+ |
static String identityString(Object x) { |
2094 |
+ |
return x.getClass().getName() |
2095 |
+ |
+ "@" + Integer.toHexString(System.identityHashCode(x)); |
2096 |
+ |
} |
2097 |
+ |
|
2098 |
+ |
// --- Shared assertions for Executor tests --- |
2099 |
+ |
|
2100 |
+ |
/** |
2101 |
+ |
* Returns maximum number of tasks that can be submitted to given |
2102 |
+ |
* pool (with bounded queue) before saturation (when submission |
2103 |
+ |
* throws RejectedExecutionException). |
2104 |
+ |
*/ |
2105 |
+ |
static final int saturatedSize(ThreadPoolExecutor pool) { |
2106 |
+ |
BlockingQueue<Runnable> q = pool.getQueue(); |
2107 |
+ |
return pool.getMaximumPoolSize() + q.size() + q.remainingCapacity(); |
2108 |
+ |
} |
2109 |
+ |
|
2110 |
+ |
@SuppressWarnings("FutureReturnValueIgnored") |
2111 |
+ |
void assertNullTaskSubmissionThrowsNullPointerException(Executor e) { |
2112 |
+ |
try { |
2113 |
+ |
e.execute((Runnable) null); |
2114 |
+ |
shouldThrow(); |
2115 |
+ |
} catch (NullPointerException success) {} |
2116 |
+ |
|
2117 |
+ |
if (! (e instanceof ExecutorService)) return; |
2118 |
+ |
ExecutorService es = (ExecutorService) e; |
2119 |
+ |
try { |
2120 |
+ |
es.submit((Runnable) null); |
2121 |
+ |
shouldThrow(); |
2122 |
+ |
} catch (NullPointerException success) {} |
2123 |
+ |
try { |
2124 |
+ |
es.submit((Runnable) null, Boolean.TRUE); |
2125 |
+ |
shouldThrow(); |
2126 |
+ |
} catch (NullPointerException success) {} |
2127 |
+ |
try { |
2128 |
+ |
es.submit((Callable<?>) null); |
2129 |
+ |
shouldThrow(); |
2130 |
+ |
} catch (NullPointerException success) {} |
2131 |
+ |
|
2132 |
+ |
if (! (e instanceof ScheduledExecutorService)) return; |
2133 |
+ |
ScheduledExecutorService ses = (ScheduledExecutorService) e; |
2134 |
+ |
try { |
2135 |
+ |
ses.schedule((Runnable) null, |
2136 |
+ |
randomTimeout(), randomTimeUnit()); |
2137 |
+ |
shouldThrow(); |
2138 |
+ |
} catch (NullPointerException success) {} |
2139 |
+ |
try { |
2140 |
+ |
ses.schedule((Callable<?>) null, |
2141 |
+ |
randomTimeout(), randomTimeUnit()); |
2142 |
+ |
shouldThrow(); |
2143 |
+ |
} catch (NullPointerException success) {} |
2144 |
+ |
try { |
2145 |
+ |
ses.scheduleAtFixedRate((Runnable) null, |
2146 |
+ |
randomTimeout(), LONG_DELAY_MS, MILLISECONDS); |
2147 |
+ |
shouldThrow(); |
2148 |
+ |
} catch (NullPointerException success) {} |
2149 |
+ |
try { |
2150 |
+ |
ses.scheduleWithFixedDelay((Runnable) null, |
2151 |
+ |
randomTimeout(), LONG_DELAY_MS, MILLISECONDS); |
2152 |
+ |
shouldThrow(); |
2153 |
+ |
} catch (NullPointerException success) {} |
2154 |
+ |
} |
2155 |
+ |
|
2156 |
+ |
void setRejectedExecutionHandler( |
2157 |
+ |
ThreadPoolExecutor p, RejectedExecutionHandler handler) { |
2158 |
+ |
p.setRejectedExecutionHandler(handler); |
2159 |
+ |
assertSame(handler, p.getRejectedExecutionHandler()); |
2160 |
+ |
} |
2161 |
+ |
|
2162 |
+ |
void assertTaskSubmissionsAreRejected(ThreadPoolExecutor p) { |
2163 |
+ |
final RejectedExecutionHandler savedHandler = p.getRejectedExecutionHandler(); |
2164 |
+ |
final long savedTaskCount = p.getTaskCount(); |
2165 |
+ |
final long savedCompletedTaskCount = p.getCompletedTaskCount(); |
2166 |
+ |
final int savedQueueSize = p.getQueue().size(); |
2167 |
+ |
final boolean stock = (p.getClass().getClassLoader() == null); |
2168 |
+ |
|
2169 |
+ |
Runnable r = () -> {}; |
2170 |
+ |
Callable<Boolean> c = () -> Boolean.TRUE; |
2171 |
+ |
|
2172 |
+ |
class Recorder implements RejectedExecutionHandler { |
2173 |
+ |
public volatile Runnable r = null; |
2174 |
+ |
public volatile ThreadPoolExecutor p = null; |
2175 |
+ |
public void reset() { r = null; p = null; } |
2176 |
+ |
public void rejectedExecution(Runnable r, ThreadPoolExecutor p) { |
2177 |
+ |
assertNull(this.r); |
2178 |
+ |
assertNull(this.p); |
2179 |
+ |
this.r = r; |
2180 |
+ |
this.p = p; |
2181 |
+ |
} |
2182 |
+ |
} |
2183 |
+ |
|
2184 |
+ |
// check custom handler is invoked exactly once per task |
2185 |
+ |
Recorder recorder = new Recorder(); |
2186 |
+ |
setRejectedExecutionHandler(p, recorder); |
2187 |
+ |
for (int i = 2; i--> 0; ) { |
2188 |
+ |
recorder.reset(); |
2189 |
+ |
p.execute(r); |
2190 |
+ |
if (stock && p.getClass() == ThreadPoolExecutor.class) |
2191 |
+ |
assertSame(r, recorder.r); |
2192 |
+ |
assertSame(p, recorder.p); |
2193 |
+ |
|
2194 |
+ |
recorder.reset(); |
2195 |
+ |
assertFalse(p.submit(r).isDone()); |
2196 |
+ |
if (stock) assertTrue(!((FutureTask) recorder.r).isDone()); |
2197 |
+ |
assertSame(p, recorder.p); |
2198 |
+ |
|
2199 |
+ |
recorder.reset(); |
2200 |
+ |
assertFalse(p.submit(r, Boolean.TRUE).isDone()); |
2201 |
+ |
if (stock) assertTrue(!((FutureTask) recorder.r).isDone()); |
2202 |
+ |
assertSame(p, recorder.p); |
2203 |
+ |
|
2204 |
+ |
recorder.reset(); |
2205 |
+ |
assertFalse(p.submit(c).isDone()); |
2206 |
+ |
if (stock) assertTrue(!((FutureTask) recorder.r).isDone()); |
2207 |
+ |
assertSame(p, recorder.p); |
2208 |
+ |
|
2209 |
+ |
if (p instanceof ScheduledExecutorService) { |
2210 |
+ |
ScheduledExecutorService s = (ScheduledExecutorService) p; |
2211 |
+ |
ScheduledFuture<?> future; |
2212 |
+ |
|
2213 |
+ |
recorder.reset(); |
2214 |
+ |
future = s.schedule(r, randomTimeout(), randomTimeUnit()); |
2215 |
+ |
assertFalse(future.isDone()); |
2216 |
+ |
if (stock) assertTrue(!((FutureTask) recorder.r).isDone()); |
2217 |
+ |
assertSame(p, recorder.p); |
2218 |
+ |
|
2219 |
+ |
recorder.reset(); |
2220 |
+ |
future = s.schedule(c, randomTimeout(), randomTimeUnit()); |
2221 |
+ |
assertFalse(future.isDone()); |
2222 |
+ |
if (stock) assertTrue(!((FutureTask) recorder.r).isDone()); |
2223 |
+ |
assertSame(p, recorder.p); |
2224 |
+ |
|
2225 |
+ |
recorder.reset(); |
2226 |
+ |
future = s.scheduleAtFixedRate(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS); |
2227 |
+ |
assertFalse(future.isDone()); |
2228 |
+ |
if (stock) assertTrue(!((FutureTask) recorder.r).isDone()); |
2229 |
+ |
assertSame(p, recorder.p); |
2230 |
+ |
|
2231 |
+ |
recorder.reset(); |
2232 |
+ |
future = s.scheduleWithFixedDelay(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS); |
2233 |
+ |
assertFalse(future.isDone()); |
2234 |
+ |
if (stock) assertTrue(!((FutureTask) recorder.r).isDone()); |
2235 |
+ |
assertSame(p, recorder.p); |
2236 |
+ |
} |
2237 |
+ |
} |
2238 |
+ |
|
2239 |
+ |
// Checking our custom handler above should be sufficient, but |
2240 |
+ |
// we add some integration tests of standard handlers. |
2241 |
+ |
final AtomicReference<Thread> thread = new AtomicReference<>(); |
2242 |
+ |
final Runnable setThread = () -> thread.set(Thread.currentThread()); |
2243 |
+ |
|
2244 |
+ |
setRejectedExecutionHandler(p, new ThreadPoolExecutor.AbortPolicy()); |
2245 |
+ |
try { |
2246 |
+ |
p.execute(setThread); |
2247 |
+ |
shouldThrow(); |
2248 |
+ |
} catch (RejectedExecutionException success) {} |
2249 |
+ |
assertNull(thread.get()); |
2250 |
+ |
|
2251 |
+ |
setRejectedExecutionHandler(p, new ThreadPoolExecutor.DiscardPolicy()); |
2252 |
+ |
p.execute(setThread); |
2253 |
+ |
assertNull(thread.get()); |
2254 |
+ |
|
2255 |
+ |
setRejectedExecutionHandler(p, new ThreadPoolExecutor.CallerRunsPolicy()); |
2256 |
+ |
p.execute(setThread); |
2257 |
+ |
if (p.isShutdown()) |
2258 |
+ |
assertNull(thread.get()); |
2259 |
+ |
else |
2260 |
+ |
assertSame(Thread.currentThread(), thread.get()); |
2261 |
+ |
|
2262 |
+ |
setRejectedExecutionHandler(p, savedHandler); |
2263 |
+ |
|
2264 |
+ |
// check that pool was not perturbed by handlers |
2265 |
+ |
assertEquals(savedTaskCount, p.getTaskCount()); |
2266 |
+ |
assertEquals(savedCompletedTaskCount, p.getCompletedTaskCount()); |
2267 |
+ |
assertEquals(savedQueueSize, p.getQueue().size()); |
2268 |
+ |
} |
2269 |
+ |
|
2270 |
+ |
void assertCollectionsEquals(Collection<?> x, Collection<?> y) { |
2271 |
+ |
assertEquals(x, y); |
2272 |
+ |
assertEquals(y, x); |
2273 |
+ |
assertEquals(x.isEmpty(), y.isEmpty()); |
2274 |
+ |
assertEquals(x.size(), y.size()); |
2275 |
+ |
if (x instanceof List) { |
2276 |
+ |
assertEquals(x.toString(), y.toString()); |
2277 |
+ |
} |
2278 |
+ |
if (x instanceof List || x instanceof Set) { |
2279 |
+ |
assertEquals(x.hashCode(), y.hashCode()); |
2280 |
+ |
} |
2281 |
+ |
if (x instanceof List || x instanceof Deque) { |
2282 |
+ |
assertTrue(Arrays.equals(x.toArray(), y.toArray())); |
2283 |
+ |
assertTrue(Arrays.equals(x.toArray(new Object[0]), |
2284 |
+ |
y.toArray(new Object[0]))); |
2285 |
+ |
} |
2286 |
+ |
} |
2287 |
+ |
|
2288 |
+ |
/** |
2289 |
+ |
* A weaker form of assertCollectionsEquals which does not insist |
2290 |
+ |
* that the two collections satisfy Object#equals(Object), since |
2291 |
+ |
* they may use identity semantics as Deques do. |
2292 |
+ |
*/ |
2293 |
+ |
void assertCollectionsEquivalent(Collection<?> x, Collection<?> y) { |
2294 |
+ |
if (x instanceof List || x instanceof Set) |
2295 |
+ |
assertCollectionsEquals(x, y); |
2296 |
+ |
else { |
2297 |
+ |
assertEquals(x.isEmpty(), y.isEmpty()); |
2298 |
+ |
assertEquals(x.size(), y.size()); |
2299 |
+ |
assertEquals(new HashSet<Object>(x), new HashSet<Object>(y)); |
2300 |
+ |
if (x instanceof Deque) { |
2301 |
+ |
assertTrue(Arrays.equals(x.toArray(), y.toArray())); |
2302 |
+ |
assertTrue(Arrays.equals(x.toArray(new Object[0]), |
2303 |
+ |
y.toArray(new Object[0]))); |
2304 |
+ |
} |
2305 |
+ |
} |
2306 |
+ |
} |
2307 |
|
} |