1 |
dl |
1.1 |
/* |
2 |
jsr166 |
1.221 |
* 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 |
jsr166 |
1.74 |
* http://creativecommons.org/publicdomain/zero/1.0/ |
6 |
jsr166 |
1.27 |
* Other contributors include Andrew Wright, Jeffrey Hayes, |
7 |
|
|
* Pat Fisher, Mike Judd. |
8 |
dl |
1.1 |
*/ |
9 |
|
|
|
10 |
jsr166 |
1.182 |
/* |
11 |
|
|
* @test |
12 |
jsr166 |
1.221 |
* @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 |
jsr166 |
1.213 |
* @build * |
16 |
|
|
* @modules java.management |
17 |
|
|
* @run junit/othervm/timeout=1000 JSR166TestCase |
18 |
jsr166 |
1.214 |
* @run junit/othervm/timeout=1000 |
19 |
jsr166 |
1.221 |
* --add-opens java.base/java.util.concurrent=ALL-UNNAMED |
20 |
|
|
* --add-opens java.base/java.lang=ALL-UNNAMED |
21 |
jsr166 |
1.214 |
* -Djsr166.testImplementationDetails=true |
22 |
|
|
* JSR166TestCase |
23 |
|
|
* @run junit/othervm/timeout=1000 |
24 |
jsr166 |
1.221 |
* --add-opens java.base/java.util.concurrent=ALL-UNNAMED |
25 |
|
|
* --add-opens java.base/java.lang=ALL-UNNAMED |
26 |
jsr166 |
1.214 |
* -Djsr166.testImplementationDetails=true |
27 |
|
|
* -Djava.util.concurrent.ForkJoinPool.common.parallelism=0 |
28 |
|
|
* JSR166TestCase |
29 |
|
|
* @run junit/othervm/timeout=1000 |
30 |
jsr166 |
1.221 |
* --add-opens java.base/java.util.concurrent=ALL-UNNAMED |
31 |
|
|
* --add-opens java.base/java.lang=ALL-UNNAMED |
32 |
jsr166 |
1.214 |
* -Djsr166.testImplementationDetails=true |
33 |
|
|
* -Djava.util.concurrent.ForkJoinPool.common.parallelism=1 |
34 |
|
|
* -Djava.util.secureRandomSeed=true |
35 |
|
|
* JSR166TestCase |
36 |
jsr166 |
1.217 |
* @run junit/othervm/timeout=1000/policy=tck.policy |
37 |
jsr166 |
1.221 |
* --add-opens java.base/java.util.concurrent=ALL-UNNAMED |
38 |
|
|
* --add-opens java.base/java.lang=ALL-UNNAMED |
39 |
jsr166 |
1.217 |
* -Djsr166.testImplementationDetails=true |
40 |
|
|
* JSR166TestCase |
41 |
jsr166 |
1.182 |
*/ |
42 |
|
|
|
43 |
jsr166 |
1.123 |
import static java.util.concurrent.TimeUnit.MILLISECONDS; |
44 |
jsr166 |
1.156 |
import static java.util.concurrent.TimeUnit.MINUTES; |
45 |
jsr166 |
1.123 |
import static java.util.concurrent.TimeUnit.NANOSECONDS; |
46 |
|
|
|
47 |
jsr166 |
1.79 |
import java.io.ByteArrayInputStream; |
48 |
|
|
import java.io.ByteArrayOutputStream; |
49 |
|
|
import java.io.ObjectInputStream; |
50 |
|
|
import java.io.ObjectOutputStream; |
51 |
jsr166 |
1.96 |
import java.lang.management.ManagementFactory; |
52 |
jsr166 |
1.268 |
import java.lang.management.LockInfo; |
53 |
jsr166 |
1.96 |
import java.lang.management.ThreadInfo; |
54 |
jsr166 |
1.150 |
import java.lang.management.ThreadMXBean; |
55 |
jsr166 |
1.134 |
import java.lang.reflect.Constructor; |
56 |
jsr166 |
1.97 |
import java.lang.reflect.Method; |
57 |
jsr166 |
1.134 |
import java.lang.reflect.Modifier; |
58 |
jsr166 |
1.123 |
import java.security.CodeSource; |
59 |
|
|
import java.security.Permission; |
60 |
|
|
import java.security.PermissionCollection; |
61 |
|
|
import java.security.Permissions; |
62 |
|
|
import java.security.Policy; |
63 |
|
|
import java.security.ProtectionDomain; |
64 |
|
|
import java.security.SecurityPermission; |
65 |
jsr166 |
1.93 |
import java.util.ArrayList; |
66 |
jsr166 |
1.72 |
import java.util.Arrays; |
67 |
jsr166 |
1.208 |
import java.util.Collection; |
68 |
jsr166 |
1.200 |
import java.util.Collections; |
69 |
jsr166 |
1.81 |
import java.util.Date; |
70 |
jsr166 |
1.243 |
import java.util.Deque; |
71 |
jsr166 |
1.93 |
import java.util.Enumeration; |
72 |
jsr166 |
1.243 |
import java.util.HashSet; |
73 |
jsr166 |
1.126 |
import java.util.Iterator; |
74 |
jsr166 |
1.93 |
import java.util.List; |
75 |
jsr166 |
1.72 |
import java.util.NoSuchElementException; |
76 |
jsr166 |
1.53 |
import java.util.PropertyPermission; |
77 |
dl |
1.272 |
import java.util.Queue; |
78 |
jsr166 |
1.243 |
import java.util.Set; |
79 |
jsr166 |
1.123 |
import java.util.concurrent.BlockingQueue; |
80 |
|
|
import java.util.concurrent.Callable; |
81 |
|
|
import java.util.concurrent.CountDownLatch; |
82 |
|
|
import java.util.concurrent.CyclicBarrier; |
83 |
jsr166 |
1.139 |
import java.util.concurrent.ExecutionException; |
84 |
jsr166 |
1.234 |
import java.util.concurrent.Executor; |
85 |
jsr166 |
1.139 |
import java.util.concurrent.Executors; |
86 |
jsr166 |
1.123 |
import java.util.concurrent.ExecutorService; |
87 |
jsr166 |
1.146 |
import java.util.concurrent.ForkJoinPool; |
88 |
jsr166 |
1.123 |
import java.util.concurrent.Future; |
89 |
jsr166 |
1.234 |
import java.util.concurrent.FutureTask; |
90 |
jsr166 |
1.123 |
import java.util.concurrent.RecursiveAction; |
91 |
|
|
import java.util.concurrent.RecursiveTask; |
92 |
jsr166 |
1.234 |
import java.util.concurrent.RejectedExecutionException; |
93 |
jsr166 |
1.123 |
import java.util.concurrent.RejectedExecutionHandler; |
94 |
|
|
import java.util.concurrent.Semaphore; |
95 |
jsr166 |
1.234 |
import java.util.concurrent.ScheduledExecutorService; |
96 |
|
|
import java.util.concurrent.ScheduledFuture; |
97 |
jsr166 |
1.193 |
import java.util.concurrent.SynchronousQueue; |
98 |
jsr166 |
1.123 |
import java.util.concurrent.ThreadFactory; |
99 |
jsr166 |
1.200 |
import java.util.concurrent.ThreadLocalRandom; |
100 |
jsr166 |
1.123 |
import java.util.concurrent.ThreadPoolExecutor; |
101 |
jsr166 |
1.232 |
import java.util.concurrent.TimeUnit; |
102 |
jsr166 |
1.123 |
import java.util.concurrent.TimeoutException; |
103 |
jsr166 |
1.185 |
import java.util.concurrent.atomic.AtomicBoolean; |
104 |
jsr166 |
1.53 |
import java.util.concurrent.atomic.AtomicReference; |
105 |
jsr166 |
1.114 |
import java.util.regex.Pattern; |
106 |
jsr166 |
1.123 |
|
107 |
|
|
import junit.framework.Test; |
108 |
|
|
import junit.framework.TestCase; |
109 |
jsr166 |
1.131 |
import junit.framework.TestResult; |
110 |
jsr166 |
1.123 |
import junit.framework.TestSuite; |
111 |
dl |
1.1 |
|
112 |
|
|
/** |
113 |
dl |
1.5 |
* Base class for JSR166 Junit TCK tests. Defines some constants, |
114 |
|
|
* utility methods and classes, as well as a simple framework for |
115 |
|
|
* helping to make sure that assertions failing in generated threads |
116 |
|
|
* cause the associated test that generated them to itself fail (which |
117 |
jsr166 |
1.27 |
* JUnit does not otherwise arrange). The rules for creating such |
118 |
dl |
1.5 |
* tests are: |
119 |
dl |
1.1 |
* |
120 |
|
|
* <ol> |
121 |
|
|
* |
122 |
jsr166 |
1.248 |
* <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 |
dl |
1.1 |
* |
138 |
jsr166 |
1.143 |
* <li>If you override {@link #setUp} or {@link #tearDown}, make sure |
139 |
jsr166 |
1.50 |
* to invoke {@code super.setUp} and {@code super.tearDown} within |
140 |
dl |
1.1 |
* them. These methods are used to clear and check for thread |
141 |
jsr166 |
1.143 |
* assertion failures. |
142 |
dl |
1.1 |
* |
143 |
jsr166 |
1.51 |
* <li>All delays and timeouts must use one of the constants {@code |
144 |
jsr166 |
1.50 |
* SHORT_DELAY_MS}, {@code SMALL_DELAY_MS}, {@code MEDIUM_DELAY_MS}, |
145 |
|
|
* {@code LONG_DELAY_MS}. The idea here is that a SHORT is always |
146 |
dl |
1.5 |
* discriminable from zero time, and always allows enough time for the |
147 |
|
|
* small amounts of computation (creating a thread, calling a few |
148 |
dl |
1.1 |
* methods, etc) needed to reach a timeout point. Similarly, a SMALL |
149 |
|
|
* is always discriminable as larger than SHORT and smaller than |
150 |
|
|
* MEDIUM. And so on. These constants are set to conservative values, |
151 |
dl |
1.2 |
* but even so, if there is ever any doubt, they can all be increased |
152 |
jsr166 |
1.143 |
* in one spot to rerun tests on slower platforms. |
153 |
dl |
1.1 |
* |
154 |
dl |
1.272 |
* Class Item is used for elements of collections and related |
155 |
jsr166 |
1.273 |
* purposes. Many tests rely on their keys being equal to ints. To |
156 |
dl |
1.272 |
* check these, methods mustEqual, mustContain, etc adapt the JUnit |
157 |
|
|
* assert methods to intercept ints. |
158 |
|
|
* |
159 |
jsr166 |
1.143 |
* <li>All threads generated must be joined inside each test case |
160 |
jsr166 |
1.50 |
* method (or {@code fail} to do so) before returning from the |
161 |
|
|
* method. The {@code joinPool} method can be used to do this when |
162 |
jsr166 |
1.143 |
* using Executors. |
163 |
dl |
1.1 |
* |
164 |
|
|
* </ol> |
165 |
dl |
1.6 |
* |
166 |
jsr166 |
1.92 |
* <p><b>Other notes</b> |
167 |
dl |
1.6 |
* <ul> |
168 |
|
|
* |
169 |
jsr166 |
1.143 |
* <li>Usually, there is one testcase method per JSR166 method |
170 |
dl |
1.6 |
* covering "normal" operation, and then as many exception-testing |
171 |
|
|
* methods as there are exceptions the method can throw. Sometimes |
172 |
|
|
* there are multiple tests per JSR166 method when the different |
173 |
|
|
* "normal" behaviors differ significantly. And sometimes testcases |
174 |
jsr166 |
1.180 |
* cover multiple methods when they cannot be tested in isolation. |
175 |
jsr166 |
1.27 |
* |
176 |
jsr166 |
1.143 |
* <li>The documentation style for testcases is to provide as javadoc |
177 |
dl |
1.6 |
* a simple sentence or two describing the property that the testcase |
178 |
|
|
* method purports to test. The javadocs do not say anything about how |
179 |
jsr166 |
1.143 |
* the property is tested. To find out, read the code. |
180 |
dl |
1.6 |
* |
181 |
jsr166 |
1.143 |
* <li>These tests are "conformance tests", and do not attempt to |
182 |
dl |
1.6 |
* test throughput, latency, scalability or other performance factors |
183 |
|
|
* (see the separate "jtreg" tests for a set intended to check these |
184 |
|
|
* for the most central aspects of functionality.) So, most tests use |
185 |
|
|
* the smallest sensible numbers of threads, collection sizes, etc |
186 |
jsr166 |
1.143 |
* needed to check basic conformance. |
187 |
dl |
1.6 |
* |
188 |
|
|
* <li>The test classes currently do not declare inclusion in |
189 |
|
|
* any particular package to simplify things for people integrating |
190 |
jsr166 |
1.143 |
* them in TCK test suites. |
191 |
dl |
1.6 |
* |
192 |
jsr166 |
1.143 |
* <li>As a convenience, the {@code main} of this class (JSR166TestCase) |
193 |
|
|
* runs all JSR166 unit tests. |
194 |
dl |
1.6 |
* |
195 |
|
|
* </ul> |
196 |
dl |
1.1 |
*/ |
197 |
|
|
public class JSR166TestCase extends TestCase { |
198 |
dl |
1.274 |
// No longer run with custom securityManagers |
199 |
jsr166 |
1.49 |
private static final boolean useSecurityManager = |
200 |
dl |
1.274 |
Boolean.getBoolean("jsr166.useSecurityManager"); |
201 |
jsr166 |
1.49 |
|
202 |
jsr166 |
1.62 |
protected static final boolean expensiveTests = |
203 |
|
|
Boolean.getBoolean("jsr166.expensiveTests"); |
204 |
|
|
|
205 |
jsr166 |
1.119 |
/** |
206 |
|
|
* If true, also run tests that are not part of the official tck |
207 |
|
|
* because they test unspecified implementation details. |
208 |
|
|
*/ |
209 |
jsr166 |
1.118 |
protected static final boolean testImplementationDetails = |
210 |
|
|
Boolean.getBoolean("jsr166.testImplementationDetails"); |
211 |
|
|
|
212 |
dl |
1.6 |
/** |
213 |
jsr166 |
1.61 |
* If true, report on stdout all "slow" tests, that is, ones that |
214 |
|
|
* take more than profileThreshold milliseconds to execute. |
215 |
|
|
*/ |
216 |
|
|
private static final boolean profileTests = |
217 |
|
|
Boolean.getBoolean("jsr166.profileTests"); |
218 |
|
|
|
219 |
|
|
/** |
220 |
|
|
* The number of milliseconds that tests are permitted for |
221 |
|
|
* execution without being reported, when profileTests is set. |
222 |
|
|
*/ |
223 |
|
|
private static final long profileThreshold = |
224 |
|
|
Long.getLong("jsr166.profileThreshold", 100); |
225 |
|
|
|
226 |
jsr166 |
1.107 |
/** |
227 |
|
|
* The number of repetitions per test (for tickling rare bugs). |
228 |
|
|
*/ |
229 |
|
|
private static final int runsPerTest = |
230 |
|
|
Integer.getInteger("jsr166.runsPerTest", 1); |
231 |
|
|
|
232 |
jsr166 |
1.114 |
/** |
233 |
jsr166 |
1.131 |
* The number of repetitions of the test suite (for finding leaks?). |
234 |
|
|
*/ |
235 |
|
|
private static final int suiteRuns = |
236 |
|
|
Integer.getInteger("jsr166.suiteRuns", 1); |
237 |
|
|
|
238 |
jsr166 |
1.189 |
/** |
239 |
|
|
* Returns the value of the system property, or NaN if not defined. |
240 |
|
|
*/ |
241 |
|
|
private static float systemPropertyValue(String name) { |
242 |
jsr166 |
1.185 |
String floatString = System.getProperty(name); |
243 |
|
|
if (floatString == null) |
244 |
jsr166 |
1.189 |
return Float.NaN; |
245 |
jsr166 |
1.185 |
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 |
jsr166 |
1.268 |
private static final ThreadMXBean THREAD_MXBEAN |
255 |
|
|
= ManagementFactory.getThreadMXBean(); |
256 |
|
|
|
257 |
jsr166 |
1.181 |
/** |
258 |
|
|
* The scaling factor to apply to standard delays used in tests. |
259 |
jsr166 |
1.189 |
* 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 |
jsr166 |
1.181 |
|
279 |
jsr166 |
1.134 |
public JSR166TestCase() { super(); } |
280 |
|
|
public JSR166TestCase(String name) { super(name); } |
281 |
|
|
|
282 |
jsr166 |
1.131 |
/** |
283 |
jsr166 |
1.114 |
* A filter for tests to run, matching strings of the form |
284 |
|
|
* methodName(className), e.g. "testInvokeAll5(ForkJoinPoolTest)" |
285 |
|
|
* Usefully combined with jsr166.runsPerTest. |
286 |
|
|
*/ |
287 |
|
|
private static final Pattern methodFilter = methodFilter(); |
288 |
|
|
|
289 |
|
|
private static Pattern methodFilter() { |
290 |
|
|
String regex = System.getProperty("jsr166.methodFilter"); |
291 |
|
|
return (regex == null) ? null : Pattern.compile(regex); |
292 |
|
|
} |
293 |
|
|
|
294 |
jsr166 |
1.170 |
// Instrumentation to debug very rare, but very annoying hung test runs. |
295 |
jsr166 |
1.156 |
static volatile TestCase currentTestCase; |
296 |
jsr166 |
1.173 |
// static volatile int currentRun = 0; |
297 |
jsr166 |
1.156 |
static { |
298 |
jsr166 |
1.265 |
Runnable wedgedTestDetector = new Runnable() { public void run() { |
299 |
jsr166 |
1.174 |
// 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 |
jsr166 |
1.255 |
final int timeoutMinutesMin = Math.max(runsPerTest / 60, 1) |
303 |
|
|
* Math.max((int) delayFactor, 1); |
304 |
|
|
final int timeoutMinutes = Math.min(15, timeoutMinutesMin); |
305 |
jsr166 |
1.156 |
for (TestCase lastTestCase = currentTestCase;;) { |
306 |
jsr166 |
1.157 |
try { MINUTES.sleep(timeoutMinutes); } |
307 |
jsr166 |
1.156 |
catch (InterruptedException unexpected) { break; } |
308 |
|
|
if (lastTestCase == currentTestCase) { |
309 |
jsr166 |
1.170 |
System.err.printf( |
310 |
jsr166 |
1.173 |
"Looks like we're stuck running test: %s%n", |
311 |
|
|
lastTestCase); |
312 |
|
|
// System.err.printf( |
313 |
|
|
// "Looks like we're stuck running test: %s (%d/%d)%n", |
314 |
|
|
// lastTestCase, currentRun, runsPerTest); |
315 |
jsr166 |
1.175 |
// System.err.println("availableProcessors=" + |
316 |
|
|
// Runtime.getRuntime().availableProcessors()); |
317 |
|
|
// System.err.printf("cpu model = %s%n", cpuModel()); |
318 |
jsr166 |
1.156 |
dumpTestThreads(); |
319 |
jsr166 |
1.165 |
// one stack dump is probably enough; more would be spam |
320 |
|
|
break; |
321 |
jsr166 |
1.156 |
} |
322 |
|
|
lastTestCase = currentTestCase; |
323 |
|
|
}}}; |
324 |
jsr166 |
1.265 |
Thread thread = new Thread(wedgedTestDetector, "WedgedTestDetector"); |
325 |
jsr166 |
1.156 |
thread.setDaemon(true); |
326 |
|
|
thread.start(); |
327 |
|
|
} |
328 |
|
|
|
329 |
jsr166 |
1.175 |
// public static String cpuModel() { |
330 |
|
|
// try { |
331 |
jsr166 |
1.220 |
// java.util.regex.Matcher matcher |
332 |
|
|
// = Pattern.compile("model name\\s*: (.*)") |
333 |
jsr166 |
1.175 |
// .matcher(new String( |
334 |
jsr166 |
1.220 |
// java.nio.file.Files.readAllBytes( |
335 |
|
|
// java.nio.file.Paths.get("/proc/cpuinfo")), "UTF-8")); |
336 |
jsr166 |
1.175 |
// matcher.find(); |
337 |
|
|
// return matcher.group(1); |
338 |
|
|
// } catch (Exception ex) { return null; } |
339 |
|
|
// } |
340 |
jsr166 |
1.171 |
|
341 |
jsr166 |
1.147 |
public void runBare() throws Throwable { |
342 |
jsr166 |
1.156 |
currentTestCase = this; |
343 |
jsr166 |
1.147 |
if (methodFilter == null |
344 |
|
|
|| methodFilter.matcher(toString()).find()) |
345 |
|
|
super.runBare(); |
346 |
|
|
} |
347 |
|
|
|
348 |
jsr166 |
1.61 |
protected void runTest() throws Throwable { |
349 |
jsr166 |
1.147 |
for (int i = 0; i < runsPerTest; i++) { |
350 |
jsr166 |
1.173 |
// currentRun = i; |
351 |
jsr166 |
1.147 |
if (profileTests) |
352 |
|
|
runTestProfiled(); |
353 |
|
|
else |
354 |
|
|
super.runTest(); |
355 |
jsr166 |
1.107 |
} |
356 |
jsr166 |
1.61 |
} |
357 |
|
|
|
358 |
|
|
protected void runTestProfiled() throws Throwable { |
359 |
jsr166 |
1.145 |
for (int i = 0; i < 2; i++) { |
360 |
|
|
long startTime = System.nanoTime(); |
361 |
jsr166 |
1.61 |
super.runTest(); |
362 |
jsr166 |
1.145 |
long elapsedMillis = millisElapsedSince(startTime); |
363 |
|
|
if (elapsedMillis < profileThreshold) |
364 |
|
|
break; |
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 |
jsr166 |
1.267 |
System.out.printf("%s: %d%n", toString(), elapsedMillis); |
369 |
jsr166 |
1.61 |
} |
370 |
|
|
} |
371 |
jsr166 |
1.63 |
|
372 |
jsr166 |
1.61 |
/** |
373 |
jsr166 |
1.94 |
* Runs all JSR166 unit tests using junit.textui.TestRunner. |
374 |
jsr166 |
1.27 |
*/ |
375 |
jsr166 |
1.41 |
public static void main(String[] args) { |
376 |
jsr166 |
1.131 |
main(suite(), args); |
377 |
|
|
} |
378 |
|
|
|
379 |
jsr166 |
1.178 |
static class PithyResultPrinter extends junit.textui.ResultPrinter { |
380 |
|
|
PithyResultPrinter(java.io.PrintStream writer) { super(writer); } |
381 |
|
|
long runTime; |
382 |
|
|
public void startTest(Test test) {} |
383 |
jsr166 |
1.179 |
protected void printHeader(long runTime) { |
384 |
jsr166 |
1.178 |
this.runTime = runTime; // defer printing for later |
385 |
jsr166 |
1.179 |
} |
386 |
|
|
protected void printFooter(TestResult result) { |
387 |
jsr166 |
1.178 |
if (result.wasSuccessful()) { |
388 |
|
|
getWriter().println("OK (" + result.runCount() + " tests)" |
389 |
|
|
+ " Time: " + elapsedTimeAsString(runTime)); |
390 |
|
|
} else { |
391 |
|
|
getWriter().println("Time: " + elapsedTimeAsString(runTime)); |
392 |
|
|
super.printFooter(result); |
393 |
|
|
} |
394 |
|
|
} |
395 |
|
|
} |
396 |
|
|
|
397 |
|
|
/** |
398 |
|
|
* Returns a TestRunner that doesn't bother with unnecessary |
399 |
|
|
* fluff, like printing a "." for each test case. |
400 |
|
|
*/ |
401 |
|
|
static junit.textui.TestRunner newPithyTestRunner() { |
402 |
|
|
junit.textui.TestRunner runner = new junit.textui.TestRunner(); |
403 |
|
|
runner.setPrinter(new PithyResultPrinter(System.out)); |
404 |
|
|
return runner; |
405 |
|
|
} |
406 |
|
|
|
407 |
jsr166 |
1.131 |
/** |
408 |
|
|
* Runs all unit tests in the given test suite. |
409 |
jsr166 |
1.132 |
* Actual behavior influenced by jsr166.* system properties. |
410 |
jsr166 |
1.131 |
*/ |
411 |
dl |
1.274 |
@SuppressWarnings("removal") |
412 |
jsr166 |
1.131 |
static void main(Test suite, String[] args) { |
413 |
jsr166 |
1.49 |
if (useSecurityManager) { |
414 |
|
|
System.err.println("Setting a permissive security manager"); |
415 |
|
|
Policy.setPolicy(permissivePolicy()); |
416 |
dl |
1.275 |
try { |
417 |
|
|
System.setSecurityManager(new SecurityManager()); |
418 |
jsr166 |
1.276 |
} catch (Throwable ok) { // failure OK during deprecation |
419 |
dl |
1.275 |
} |
420 |
jsr166 |
1.49 |
} |
421 |
jsr166 |
1.131 |
for (int i = 0; i < suiteRuns; i++) { |
422 |
jsr166 |
1.178 |
TestResult result = newPithyTestRunner().doRun(suite); |
423 |
jsr166 |
1.131 |
if (!result.wasSuccessful()) |
424 |
|
|
System.exit(1); |
425 |
dl |
1.22 |
System.gc(); |
426 |
|
|
System.runFinalization(); |
427 |
|
|
} |
428 |
dl |
1.6 |
} |
429 |
|
|
|
430 |
jsr166 |
1.60 |
public static TestSuite newTestSuite(Object... suiteOrClasses) { |
431 |
|
|
TestSuite suite = new TestSuite(); |
432 |
|
|
for (Object suiteOrClass : suiteOrClasses) { |
433 |
|
|
if (suiteOrClass instanceof TestSuite) |
434 |
|
|
suite.addTest((TestSuite) suiteOrClass); |
435 |
|
|
else if (suiteOrClass instanceof Class) |
436 |
|
|
suite.addTest(new TestSuite((Class<?>) suiteOrClass)); |
437 |
|
|
else |
438 |
|
|
throw new ClassCastException("not a test suite or class"); |
439 |
|
|
} |
440 |
|
|
return suite; |
441 |
|
|
} |
442 |
|
|
|
443 |
jsr166 |
1.98 |
public static void addNamedTestClasses(TestSuite suite, |
444 |
|
|
String... testClassNames) { |
445 |
|
|
for (String testClassName : testClassNames) { |
446 |
|
|
try { |
447 |
|
|
Class<?> testClass = Class.forName(testClassName); |
448 |
jsr166 |
1.241 |
Method m = testClass.getDeclaredMethod("suite"); |
449 |
jsr166 |
1.98 |
suite.addTest(newTestSuite((Test)m.invoke(null))); |
450 |
jsr166 |
1.241 |
} catch (ReflectiveOperationException e) { |
451 |
|
|
throw new AssertionError("Missing test class", e); |
452 |
jsr166 |
1.98 |
} |
453 |
jsr166 |
1.97 |
} |
454 |
|
|
} |
455 |
|
|
|
456 |
|
|
public static final double JAVA_CLASS_VERSION; |
457 |
jsr166 |
1.115 |
public static final String JAVA_SPECIFICATION_VERSION; |
458 |
jsr166 |
1.97 |
static { |
459 |
|
|
try { |
460 |
dl |
1.274 |
@SuppressWarnings("removal") double jcv = |
461 |
|
|
java.security.AccessController.doPrivileged( |
462 |
jsr166 |
1.97 |
new java.security.PrivilegedAction<Double>() { |
463 |
|
|
public Double run() { |
464 |
|
|
return Double.valueOf(System.getProperty("java.class.version"));}}); |
465 |
dl |
1.274 |
JAVA_CLASS_VERSION = jcv; |
466 |
|
|
@SuppressWarnings("removal") String jsv = |
467 |
|
|
java.security.AccessController.doPrivileged( |
468 |
jsr166 |
1.115 |
new java.security.PrivilegedAction<String>() { |
469 |
|
|
public String run() { |
470 |
|
|
return System.getProperty("java.specification.version");}}); |
471 |
dl |
1.274 |
JAVA_SPECIFICATION_VERSION = jsv; |
472 |
jsr166 |
1.97 |
} catch (Throwable t) { |
473 |
|
|
throw new Error(t); |
474 |
|
|
} |
475 |
|
|
} |
476 |
|
|
|
477 |
jsr166 |
1.238 |
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 |
jsr166 |
1.244 |
public static boolean atLeastJava11() { return JAVA_CLASS_VERSION >= 55.0; } |
483 |
jsr166 |
1.252 |
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 |
jsr166 |
1.97 |
|
490 |
dl |
1.6 |
/** |
491 |
jsr166 |
1.60 |
* Collects all JSR166 unit tests as one suite. |
492 |
jsr166 |
1.27 |
*/ |
493 |
jsr166 |
1.41 |
public static Test suite() { |
494 |
jsr166 |
1.98 |
// Java7+ test classes |
495 |
jsr166 |
1.97 |
TestSuite suite = newTestSuite( |
496 |
jsr166 |
1.60 |
ForkJoinPoolTest.suite(), |
497 |
|
|
ForkJoinTaskTest.suite(), |
498 |
|
|
RecursiveActionTest.suite(), |
499 |
|
|
RecursiveTaskTest.suite(), |
500 |
|
|
LinkedTransferQueueTest.suite(), |
501 |
|
|
PhaserTest.suite(), |
502 |
|
|
ThreadLocalRandomTest.suite(), |
503 |
|
|
AbstractExecutorServiceTest.suite(), |
504 |
|
|
AbstractQueueTest.suite(), |
505 |
|
|
AbstractQueuedSynchronizerTest.suite(), |
506 |
|
|
AbstractQueuedLongSynchronizerTest.suite(), |
507 |
|
|
ArrayBlockingQueueTest.suite(), |
508 |
|
|
ArrayDequeTest.suite(), |
509 |
jsr166 |
1.205 |
ArrayListTest.suite(), |
510 |
jsr166 |
1.60 |
AtomicBooleanTest.suite(), |
511 |
|
|
AtomicIntegerArrayTest.suite(), |
512 |
|
|
AtomicIntegerFieldUpdaterTest.suite(), |
513 |
|
|
AtomicIntegerTest.suite(), |
514 |
|
|
AtomicLongArrayTest.suite(), |
515 |
|
|
AtomicLongFieldUpdaterTest.suite(), |
516 |
|
|
AtomicLongTest.suite(), |
517 |
|
|
AtomicMarkableReferenceTest.suite(), |
518 |
|
|
AtomicReferenceArrayTest.suite(), |
519 |
|
|
AtomicReferenceFieldUpdaterTest.suite(), |
520 |
|
|
AtomicReferenceTest.suite(), |
521 |
|
|
AtomicStampedReferenceTest.suite(), |
522 |
|
|
ConcurrentHashMapTest.suite(), |
523 |
|
|
ConcurrentLinkedDequeTest.suite(), |
524 |
|
|
ConcurrentLinkedQueueTest.suite(), |
525 |
|
|
ConcurrentSkipListMapTest.suite(), |
526 |
|
|
ConcurrentSkipListSubMapTest.suite(), |
527 |
|
|
ConcurrentSkipListSetTest.suite(), |
528 |
|
|
ConcurrentSkipListSubSetTest.suite(), |
529 |
|
|
CopyOnWriteArrayListTest.suite(), |
530 |
|
|
CopyOnWriteArraySetTest.suite(), |
531 |
|
|
CountDownLatchTest.suite(), |
532 |
jsr166 |
1.204 |
CountedCompleterTest.suite(), |
533 |
jsr166 |
1.60 |
CyclicBarrierTest.suite(), |
534 |
|
|
DelayQueueTest.suite(), |
535 |
|
|
EntryTest.suite(), |
536 |
|
|
ExchangerTest.suite(), |
537 |
|
|
ExecutorsTest.suite(), |
538 |
|
|
ExecutorCompletionServiceTest.suite(), |
539 |
|
|
FutureTaskTest.suite(), |
540 |
jsr166 |
1.254 |
HashtableTest.suite(), |
541 |
jsr166 |
1.60 |
LinkedBlockingDequeTest.suite(), |
542 |
|
|
LinkedBlockingQueueTest.suite(), |
543 |
|
|
LinkedListTest.suite(), |
544 |
|
|
LockSupportTest.suite(), |
545 |
|
|
PriorityBlockingQueueTest.suite(), |
546 |
|
|
PriorityQueueTest.suite(), |
547 |
|
|
ReentrantLockTest.suite(), |
548 |
|
|
ReentrantReadWriteLockTest.suite(), |
549 |
|
|
ScheduledExecutorTest.suite(), |
550 |
|
|
ScheduledExecutorSubclassTest.suite(), |
551 |
|
|
SemaphoreTest.suite(), |
552 |
|
|
SynchronousQueueTest.suite(), |
553 |
|
|
SystemTest.suite(), |
554 |
|
|
ThreadLocalTest.suite(), |
555 |
|
|
ThreadPoolExecutorTest.suite(), |
556 |
|
|
ThreadPoolExecutorSubclassTest.suite(), |
557 |
|
|
ThreadTest.suite(), |
558 |
|
|
TimeUnitTest.suite(), |
559 |
|
|
TreeMapTest.suite(), |
560 |
|
|
TreeSetTest.suite(), |
561 |
|
|
TreeSubMapTest.suite(), |
562 |
jsr166 |
1.207 |
TreeSubSetTest.suite(), |
563 |
|
|
VectorTest.suite()); |
564 |
jsr166 |
1.98 |
|
565 |
|
|
// Java8+ test classes |
566 |
|
|
if (atLeastJava8()) { |
567 |
|
|
String[] java8TestClassNames = { |
568 |
jsr166 |
1.206 |
"ArrayDeque8Test", |
569 |
dl |
1.113 |
"Atomic8Test", |
570 |
dl |
1.104 |
"CompletableFutureTest", |
571 |
dl |
1.105 |
"ConcurrentHashMap8Test", |
572 |
jsr166 |
1.204 |
"CountedCompleter8Test", |
573 |
dl |
1.104 |
"DoubleAccumulatorTest", |
574 |
dl |
1.103 |
"DoubleAdderTest", |
575 |
jsr166 |
1.102 |
"ForkJoinPool8Test", |
576 |
dl |
1.111 |
"ForkJoinTask8Test", |
577 |
jsr166 |
1.237 |
"HashMapTest", |
578 |
jsr166 |
1.215 |
"LinkedBlockingDeque8Test", |
579 |
|
|
"LinkedBlockingQueue8Test", |
580 |
jsr166 |
1.251 |
"LinkedHashMapTest", |
581 |
dl |
1.104 |
"LongAccumulatorTest", |
582 |
|
|
"LongAdderTest", |
583 |
jsr166 |
1.110 |
"SplittableRandomTest", |
584 |
jsr166 |
1.98 |
"StampedLockTest", |
585 |
dl |
1.140 |
"SubmissionPublisherTest", |
586 |
jsr166 |
1.112 |
"ThreadLocalRandom8Test", |
587 |
jsr166 |
1.190 |
"TimeUnit8Test", |
588 |
jsr166 |
1.98 |
}; |
589 |
|
|
addNamedTestClasses(suite, java8TestClassNames); |
590 |
jsr166 |
1.97 |
} |
591 |
jsr166 |
1.98 |
|
592 |
jsr166 |
1.115 |
// Java9+ test classes |
593 |
|
|
if (atLeastJava9()) { |
594 |
|
|
String[] java9TestClassNames = { |
595 |
jsr166 |
1.196 |
"AtomicBoolean9Test", |
596 |
|
|
"AtomicInteger9Test", |
597 |
|
|
"AtomicIntegerArray9Test", |
598 |
|
|
"AtomicLong9Test", |
599 |
|
|
"AtomicLongArray9Test", |
600 |
|
|
"AtomicReference9Test", |
601 |
|
|
"AtomicReferenceArray9Test", |
602 |
jsr166 |
1.192 |
"ExecutorCompletionService9Test", |
603 |
jsr166 |
1.218 |
"ForkJoinPool9Test", |
604 |
jsr166 |
1.115 |
}; |
605 |
|
|
addNamedTestClasses(suite, java9TestClassNames); |
606 |
|
|
} |
607 |
|
|
|
608 |
dl |
1.274 |
if (atLeastJava17()) { |
609 |
|
|
String[] java17TestClassNames = { |
610 |
|
|
"ForkJoinPool19Test", |
611 |
|
|
}; |
612 |
|
|
addNamedTestClasses(suite, java17TestClassNames); |
613 |
|
|
} |
614 |
jsr166 |
1.97 |
return suite; |
615 |
dl |
1.6 |
} |
616 |
|
|
|
617 |
jsr166 |
1.134 |
/** 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 |
jsr166 |
1.216 |
ArrayList<String> names = new ArrayList<>(methods.length); |
621 |
jsr166 |
1.134 |
for (Method method : methods) { |
622 |
|
|
if (method.getName().startsWith("test") |
623 |
|
|
&& Modifier.isPublic(method.getModifiers()) |
624 |
|
|
// method.getParameterCount() requires jdk8+ |
625 |
|
|
&& method.getParameterTypes().length == 0) { |
626 |
|
|
names.add(method.getName()); |
627 |
|
|
} |
628 |
|
|
} |
629 |
|
|
return names; |
630 |
|
|
} |
631 |
|
|
|
632 |
|
|
/** |
633 |
|
|
* Returns junit-style testSuite for the given test class, but |
634 |
|
|
* parameterized by passing extra data to each test. |
635 |
|
|
*/ |
636 |
|
|
public static <ExtraData> Test parameterizedTestSuite |
637 |
|
|
(Class<? extends JSR166TestCase> testClass, |
638 |
|
|
Class<ExtraData> dataClass, |
639 |
|
|
ExtraData data) { |
640 |
|
|
try { |
641 |
|
|
TestSuite suite = new TestSuite(); |
642 |
|
|
Constructor c = |
643 |
|
|
testClass.getDeclaredConstructor(dataClass, String.class); |
644 |
|
|
for (String methodName : testMethodNames(testClass)) |
645 |
|
|
suite.addTest((Test) c.newInstance(data, methodName)); |
646 |
|
|
return suite; |
647 |
jsr166 |
1.241 |
} catch (ReflectiveOperationException e) { |
648 |
|
|
throw new AssertionError(e); |
649 |
jsr166 |
1.134 |
} |
650 |
|
|
} |
651 |
|
|
|
652 |
|
|
/** |
653 |
|
|
* Returns junit-style testSuite for the jdk8 extension of the |
654 |
|
|
* given test class, but parameterized by passing extra data to |
655 |
|
|
* each test. Uses reflection to allow compilation in jdk7. |
656 |
|
|
*/ |
657 |
|
|
public static <ExtraData> Test jdk8ParameterizedTestSuite |
658 |
|
|
(Class<? extends JSR166TestCase> testClass, |
659 |
|
|
Class<ExtraData> dataClass, |
660 |
|
|
ExtraData data) { |
661 |
|
|
if (atLeastJava8()) { |
662 |
|
|
String name = testClass.getName(); |
663 |
|
|
String name8 = name.replaceAll("Test$", "8Test"); |
664 |
jsr166 |
1.241 |
if (name.equals(name8)) throw new AssertionError(name); |
665 |
jsr166 |
1.134 |
try { |
666 |
|
|
return (Test) |
667 |
|
|
Class.forName(name8) |
668 |
jsr166 |
1.241 |
.getMethod("testSuite", dataClass) |
669 |
jsr166 |
1.134 |
.invoke(null, data); |
670 |
jsr166 |
1.241 |
} catch (ReflectiveOperationException e) { |
671 |
|
|
throw new AssertionError(e); |
672 |
jsr166 |
1.134 |
} |
673 |
|
|
} else { |
674 |
|
|
return new TestSuite(); |
675 |
|
|
} |
676 |
|
|
} |
677 |
|
|
|
678 |
jsr166 |
1.109 |
// Delays for timing-dependent tests, in milliseconds. |
679 |
dl |
1.1 |
|
680 |
dl |
1.2 |
public static long SHORT_DELAY_MS; |
681 |
|
|
public static long SMALL_DELAY_MS; |
682 |
|
|
public static long MEDIUM_DELAY_MS; |
683 |
|
|
public static long LONG_DELAY_MS; |
684 |
|
|
|
685 |
jsr166 |
1.261 |
/** |
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 |
jsr166 |
1.232 |
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 |
dl |
1.2 |
/** |
719 |
jsr166 |
1.256 |
* Returns a random boolean; a "coin flip". |
720 |
|
|
*/ |
721 |
|
|
static boolean randomBoolean() { |
722 |
|
|
return ThreadLocalRandom.current().nextBoolean(); |
723 |
|
|
} |
724 |
|
|
|
725 |
|
|
/** |
726 |
jsr166 |
1.257 |
* Returns a random element from given choices. |
727 |
|
|
*/ |
728 |
jsr166 |
1.270 |
<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 |
dl |
1.272 |
@SuppressWarnings("unchecked") |
736 |
jsr166 |
1.257 |
<T> T chooseRandomly(T... choices) { |
737 |
|
|
return choices[ThreadLocalRandom.current().nextInt(choices.length)]; |
738 |
|
|
} |
739 |
|
|
|
740 |
|
|
/** |
741 |
jsr166 |
1.181 |
* Returns the shortest timed delay. This can be scaled up for |
742 |
jsr166 |
1.185 |
* slow machines using the jsr166.delay.factor system property, |
743 |
jsr166 |
1.187 |
* or via jtreg's -timeoutFactor: flag. |
744 |
jsr166 |
1.185 |
* http://openjdk.java.net/jtreg/command-help.html |
745 |
jsr166 |
1.27 |
*/ |
746 |
dl |
1.2 |
protected long getShortDelay() { |
747 |
jsr166 |
1.189 |
return (long) (50 * delayFactor); |
748 |
dl |
1.2 |
} |
749 |
|
|
|
750 |
|
|
/** |
751 |
jsr166 |
1.27 |
* Sets delays as multiples of SHORT_DELAY. |
752 |
dl |
1.2 |
*/ |
753 |
jsr166 |
1.43 |
protected void setDelays() { |
754 |
dl |
1.2 |
SHORT_DELAY_MS = getShortDelay(); |
755 |
jsr166 |
1.53 |
SMALL_DELAY_MS = SHORT_DELAY_MS * 5; |
756 |
dl |
1.2 |
MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10; |
757 |
jsr166 |
1.71 |
LONG_DELAY_MS = SHORT_DELAY_MS * 200; |
758 |
jsr166 |
1.261 |
LONGER_DELAY_MS = 2 * LONG_DELAY_MS; |
759 |
dl |
1.2 |
} |
760 |
|
|
|
761 |
jsr166 |
1.223 |
private static final long TIMEOUT_DELAY_MS |
762 |
|
|
= (long) (12.0 * Math.cbrt(delayFactor)); |
763 |
|
|
|
764 |
dl |
1.1 |
/** |
765 |
jsr166 |
1.223 |
* 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 |
jsr166 |
1.81 |
*/ |
770 |
jsr166 |
1.223 |
static long timeoutMillis() { |
771 |
|
|
return TIMEOUT_DELAY_MS; |
772 |
jsr166 |
1.81 |
} |
773 |
|
|
|
774 |
|
|
/** |
775 |
jsr166 |
1.135 |
* Returns a new Date instance representing a time at least |
776 |
|
|
* delayMillis milliseconds in the future. |
777 |
jsr166 |
1.81 |
*/ |
778 |
|
|
Date delayedDate(long delayMillis) { |
779 |
jsr166 |
1.135 |
// Add 1 because currentTimeMillis is known to round into the past. |
780 |
|
|
return new Date(System.currentTimeMillis() + delayMillis + 1); |
781 |
jsr166 |
1.81 |
} |
782 |
|
|
|
783 |
|
|
/** |
784 |
jsr166 |
1.53 |
* The first exception encountered if any threadAssertXXX method fails. |
785 |
dl |
1.1 |
*/ |
786 |
jsr166 |
1.53 |
private final AtomicReference<Throwable> threadFailure |
787 |
jsr166 |
1.216 |
= new AtomicReference<>(null); |
788 |
dl |
1.1 |
|
789 |
|
|
/** |
790 |
jsr166 |
1.53 |
* Records an exception so that it can be rethrown later in the test |
791 |
|
|
* harness thread, triggering a test case failure. Only the first |
792 |
|
|
* failure is recorded; subsequent calls to this method from within |
793 |
|
|
* the same test have no effect. |
794 |
dl |
1.1 |
*/ |
795 |
jsr166 |
1.53 |
public void threadRecordFailure(Throwable t) { |
796 |
jsr166 |
1.158 |
System.err.println(t); |
797 |
jsr166 |
1.260 |
if (threadFailure.compareAndSet(null, t)) |
798 |
|
|
dumpTestThreads(); |
799 |
jsr166 |
1.53 |
} |
800 |
|
|
|
801 |
jsr166 |
1.27 |
public void setUp() { |
802 |
dl |
1.2 |
setDelays(); |
803 |
dl |
1.1 |
} |
804 |
|
|
|
805 |
jsr166 |
1.146 |
void tearDownFail(String format, Object... args) { |
806 |
|
|
String msg = toString() + ": " + String.format(format, args); |
807 |
|
|
System.err.println(msg); |
808 |
jsr166 |
1.156 |
dumpTestThreads(); |
809 |
jsr166 |
1.239 |
throw new AssertionError(msg); |
810 |
jsr166 |
1.146 |
} |
811 |
|
|
|
812 |
dl |
1.1 |
/** |
813 |
jsr166 |
1.85 |
* Extra checks that get done for all test cases. |
814 |
|
|
* |
815 |
jsr166 |
1.53 |
* Triggers test case failure if any thread assertions have failed, |
816 |
|
|
* by rethrowing, in the test harness thread, any exception recorded |
817 |
|
|
* earlier by threadRecordFailure. |
818 |
jsr166 |
1.85 |
* |
819 |
|
|
* Triggers test case failure if interrupt status is set in the main thread. |
820 |
jsr166 |
1.53 |
*/ |
821 |
|
|
public void tearDown() throws Exception { |
822 |
jsr166 |
1.70 |
Throwable t = threadFailure.getAndSet(null); |
823 |
jsr166 |
1.53 |
if (t != null) { |
824 |
|
|
if (t instanceof Error) |
825 |
|
|
throw (Error) t; |
826 |
|
|
else if (t instanceof RuntimeException) |
827 |
|
|
throw (RuntimeException) t; |
828 |
|
|
else if (t instanceof Exception) |
829 |
|
|
throw (Exception) t; |
830 |
jsr166 |
1.239 |
else |
831 |
|
|
throw new AssertionError(t.toString(), t); |
832 |
jsr166 |
1.53 |
} |
833 |
jsr166 |
1.85 |
|
834 |
|
|
if (Thread.interrupted()) |
835 |
jsr166 |
1.146 |
tearDownFail("interrupt status set in main thread"); |
836 |
jsr166 |
1.100 |
|
837 |
|
|
checkForkJoinPoolThreadLeaks(); |
838 |
dl |
1.1 |
} |
839 |
|
|
|
840 |
dl |
1.5 |
/** |
841 |
jsr166 |
1.164 |
* Finds missing PoolCleaners |
842 |
jsr166 |
1.100 |
*/ |
843 |
|
|
void checkForkJoinPoolThreadLeaks() throws InterruptedException { |
844 |
jsr166 |
1.146 |
Thread[] survivors = new Thread[7]; |
845 |
jsr166 |
1.100 |
int count = Thread.enumerate(survivors); |
846 |
|
|
for (int i = 0; i < count; i++) { |
847 |
|
|
Thread thread = survivors[i]; |
848 |
|
|
String name = thread.getName(); |
849 |
|
|
if (name.startsWith("ForkJoinPool-")) { |
850 |
|
|
// give thread some time to terminate |
851 |
|
|
thread.join(LONG_DELAY_MS); |
852 |
jsr166 |
1.146 |
if (thread.isAlive()) |
853 |
|
|
tearDownFail("Found leaked ForkJoinPool thread thread=%s", |
854 |
|
|
thread); |
855 |
jsr166 |
1.100 |
} |
856 |
|
|
} |
857 |
jsr166 |
1.146 |
|
858 |
|
|
if (!ForkJoinPool.commonPool() |
859 |
|
|
.awaitQuiescence(LONG_DELAY_MS, MILLISECONDS)) |
860 |
|
|
tearDownFail("ForkJoin common pool thread stuck"); |
861 |
jsr166 |
1.100 |
} |
862 |
jsr166 |
1.101 |
|
863 |
jsr166 |
1.100 |
/** |
864 |
jsr166 |
1.53 |
* Just like fail(reason), but additionally recording (using |
865 |
jsr166 |
1.239 |
* threadRecordFailure) any AssertionError thrown, so that the |
866 |
|
|
* current testcase will fail. |
867 |
jsr166 |
1.27 |
*/ |
868 |
dl |
1.1 |
public void threadFail(String reason) { |
869 |
jsr166 |
1.53 |
try { |
870 |
|
|
fail(reason); |
871 |
jsr166 |
1.239 |
} catch (AssertionError fail) { |
872 |
|
|
threadRecordFailure(fail); |
873 |
|
|
throw fail; |
874 |
jsr166 |
1.53 |
} |
875 |
dl |
1.1 |
} |
876 |
|
|
|
877 |
dl |
1.5 |
/** |
878 |
jsr166 |
1.53 |
* Just like assertTrue(b), but additionally recording (using |
879 |
jsr166 |
1.239 |
* threadRecordFailure) any AssertionError thrown, so that the |
880 |
|
|
* current testcase will fail. |
881 |
jsr166 |
1.27 |
*/ |
882 |
dl |
1.1 |
public void threadAssertTrue(boolean b) { |
883 |
jsr166 |
1.53 |
try { |
884 |
dl |
1.1 |
assertTrue(b); |
885 |
jsr166 |
1.239 |
} catch (AssertionError fail) { |
886 |
|
|
threadRecordFailure(fail); |
887 |
|
|
throw fail; |
888 |
dl |
1.1 |
} |
889 |
|
|
} |
890 |
dl |
1.5 |
|
891 |
|
|
/** |
892 |
jsr166 |
1.53 |
* Just like assertFalse(b), but additionally recording (using |
893 |
jsr166 |
1.239 |
* threadRecordFailure) any AssertionError thrown, so that the |
894 |
|
|
* current testcase will fail. |
895 |
jsr166 |
1.27 |
*/ |
896 |
dl |
1.1 |
public void threadAssertFalse(boolean b) { |
897 |
jsr166 |
1.53 |
try { |
898 |
dl |
1.1 |
assertFalse(b); |
899 |
jsr166 |
1.239 |
} catch (AssertionError fail) { |
900 |
|
|
threadRecordFailure(fail); |
901 |
|
|
throw fail; |
902 |
dl |
1.1 |
} |
903 |
|
|
} |
904 |
dl |
1.5 |
|
905 |
|
|
/** |
906 |
jsr166 |
1.53 |
* Just like assertNull(x), but additionally recording (using |
907 |
jsr166 |
1.239 |
* threadRecordFailure) any AssertionError thrown, so that the |
908 |
|
|
* current testcase will fail. |
909 |
jsr166 |
1.27 |
*/ |
910 |
dl |
1.1 |
public void threadAssertNull(Object x) { |
911 |
jsr166 |
1.53 |
try { |
912 |
dl |
1.1 |
assertNull(x); |
913 |
jsr166 |
1.239 |
} catch (AssertionError fail) { |
914 |
|
|
threadRecordFailure(fail); |
915 |
|
|
throw fail; |
916 |
dl |
1.1 |
} |
917 |
|
|
} |
918 |
dl |
1.5 |
|
919 |
|
|
/** |
920 |
jsr166 |
1.53 |
* Just like assertEquals(x, y), but additionally recording (using |
921 |
jsr166 |
1.239 |
* threadRecordFailure) any AssertionError thrown, so that the |
922 |
|
|
* current testcase will fail. |
923 |
jsr166 |
1.27 |
*/ |
924 |
dl |
1.1 |
public void threadAssertEquals(long x, long y) { |
925 |
jsr166 |
1.53 |
try { |
926 |
dl |
1.1 |
assertEquals(x, y); |
927 |
jsr166 |
1.239 |
} catch (AssertionError fail) { |
928 |
|
|
threadRecordFailure(fail); |
929 |
|
|
throw fail; |
930 |
dl |
1.1 |
} |
931 |
|
|
} |
932 |
dl |
1.5 |
|
933 |
|
|
/** |
934 |
jsr166 |
1.53 |
* Just like assertEquals(x, y), but additionally recording (using |
935 |
jsr166 |
1.239 |
* threadRecordFailure) any AssertionError thrown, so that the |
936 |
|
|
* current testcase will fail. |
937 |
jsr166 |
1.27 |
*/ |
938 |
dl |
1.1 |
public void threadAssertEquals(Object x, Object y) { |
939 |
jsr166 |
1.53 |
try { |
940 |
dl |
1.1 |
assertEquals(x, y); |
941 |
jsr166 |
1.239 |
} catch (AssertionError fail) { |
942 |
jsr166 |
1.129 |
threadRecordFailure(fail); |
943 |
|
|
throw fail; |
944 |
|
|
} catch (Throwable fail) { |
945 |
|
|
threadUnexpectedException(fail); |
946 |
dl |
1.1 |
} |
947 |
|
|
} |
948 |
|
|
|
949 |
dl |
1.5 |
/** |
950 |
jsr166 |
1.53 |
* Just like assertSame(x, y), but additionally recording (using |
951 |
jsr166 |
1.239 |
* threadRecordFailure) any AssertionError thrown, so that the |
952 |
|
|
* current testcase will fail. |
953 |
jsr166 |
1.52 |
*/ |
954 |
|
|
public void threadAssertSame(Object x, Object y) { |
955 |
jsr166 |
1.53 |
try { |
956 |
jsr166 |
1.52 |
assertSame(x, y); |
957 |
jsr166 |
1.239 |
} catch (AssertionError fail) { |
958 |
jsr166 |
1.129 |
threadRecordFailure(fail); |
959 |
|
|
throw fail; |
960 |
jsr166 |
1.52 |
} |
961 |
|
|
} |
962 |
|
|
|
963 |
|
|
/** |
964 |
jsr166 |
1.53 |
* Calls threadFail with message "should throw exception". |
965 |
jsr166 |
1.33 |
*/ |
966 |
dl |
1.3 |
public void threadShouldThrow() { |
967 |
jsr166 |
1.53 |
threadFail("should throw exception"); |
968 |
dl |
1.3 |
} |
969 |
|
|
|
970 |
dl |
1.5 |
/** |
971 |
jsr166 |
1.53 |
* Calls threadFail with message "should throw" + exceptionName. |
972 |
jsr166 |
1.40 |
*/ |
973 |
|
|
public void threadShouldThrow(String exceptionName) { |
974 |
jsr166 |
1.53 |
threadFail("should throw " + exceptionName); |
975 |
dl |
1.3 |
} |
976 |
|
|
|
977 |
dl |
1.31 |
/** |
978 |
jsr166 |
1.57 |
* Records the given exception using {@link #threadRecordFailure}, |
979 |
jsr166 |
1.239 |
* then rethrows the exception, wrapping it in an AssertionError |
980 |
|
|
* if necessary. |
981 |
dl |
1.31 |
*/ |
982 |
jsr166 |
1.53 |
public void threadUnexpectedException(Throwable t) { |
983 |
|
|
threadRecordFailure(t); |
984 |
|
|
t.printStackTrace(); |
985 |
|
|
if (t instanceof RuntimeException) |
986 |
|
|
throw (RuntimeException) t; |
987 |
|
|
else if (t instanceof Error) |
988 |
|
|
throw (Error) t; |
989 |
jsr166 |
1.239 |
else |
990 |
|
|
throw new AssertionError("unexpected exception: " + t, t); |
991 |
dl |
1.31 |
} |
992 |
dl |
1.3 |
|
993 |
dl |
1.1 |
/** |
994 |
jsr166 |
1.81 |
* Delays, via Thread.sleep, for the given millisecond delay, but |
995 |
dl |
1.76 |
* if the sleep is shorter than specified, may re-sleep or yield |
996 |
jsr166 |
1.163 |
* until time elapses. Ensures that the given time, as measured |
997 |
|
|
* by System.nanoTime(), has elapsed. |
998 |
dl |
1.76 |
*/ |
999 |
jsr166 |
1.81 |
static void delay(long millis) throws InterruptedException { |
1000 |
jsr166 |
1.163 |
long nanos = millis * (1000 * 1000); |
1001 |
|
|
final long wakeupTime = System.nanoTime() + nanos; |
1002 |
|
|
do { |
1003 |
jsr166 |
1.80 |
if (millis > 0L) |
1004 |
|
|
Thread.sleep(millis); |
1005 |
dl |
1.76 |
else // too short to sleep |
1006 |
|
|
Thread.yield(); |
1007 |
jsr166 |
1.163 |
nanos = wakeupTime - System.nanoTime(); |
1008 |
|
|
millis = nanos / (1000 * 1000); |
1009 |
|
|
} while (nanos >= 0L); |
1010 |
dl |
1.76 |
} |
1011 |
|
|
|
1012 |
|
|
/** |
1013 |
jsr166 |
1.149 |
* Allows use of try-with-resources with per-test thread pools. |
1014 |
|
|
*/ |
1015 |
jsr166 |
1.160 |
class PoolCleaner implements AutoCloseable { |
1016 |
|
|
private final ExecutorService pool; |
1017 |
|
|
public PoolCleaner(ExecutorService pool) { this.pool = pool; } |
1018 |
jsr166 |
1.149 |
public void close() { joinPool(pool); } |
1019 |
|
|
} |
1020 |
|
|
|
1021 |
jsr166 |
1.166 |
/** |
1022 |
|
|
* An extension of PoolCleaner that has an action to release the pool. |
1023 |
|
|
*/ |
1024 |
|
|
class PoolCleanerWithReleaser extends PoolCleaner { |
1025 |
|
|
private final Runnable releaser; |
1026 |
|
|
public PoolCleanerWithReleaser(ExecutorService pool, Runnable releaser) { |
1027 |
|
|
super(pool); |
1028 |
|
|
this.releaser = releaser; |
1029 |
|
|
} |
1030 |
|
|
public void close() { |
1031 |
|
|
try { |
1032 |
|
|
releaser.run(); |
1033 |
|
|
} finally { |
1034 |
|
|
super.close(); |
1035 |
|
|
} |
1036 |
|
|
} |
1037 |
|
|
} |
1038 |
|
|
|
1039 |
jsr166 |
1.160 |
PoolCleaner cleaner(ExecutorService pool) { |
1040 |
|
|
return new PoolCleaner(pool); |
1041 |
jsr166 |
1.159 |
} |
1042 |
|
|
|
1043 |
jsr166 |
1.166 |
PoolCleaner cleaner(ExecutorService pool, Runnable releaser) { |
1044 |
|
|
return new PoolCleanerWithReleaser(pool, releaser); |
1045 |
|
|
} |
1046 |
|
|
|
1047 |
|
|
PoolCleaner cleaner(ExecutorService pool, CountDownLatch latch) { |
1048 |
|
|
return new PoolCleanerWithReleaser(pool, releaser(latch)); |
1049 |
|
|
} |
1050 |
|
|
|
1051 |
|
|
Runnable releaser(final CountDownLatch latch) { |
1052 |
|
|
return new Runnable() { public void run() { |
1053 |
|
|
do { latch.countDown(); } |
1054 |
|
|
while (latch.getCount() > 0); |
1055 |
|
|
}}; |
1056 |
|
|
} |
1057 |
|
|
|
1058 |
jsr166 |
1.185 |
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 |
jsr166 |
1.149 |
/** |
1067 |
jsr166 |
1.53 |
* Waits out termination of a thread pool or fails doing so. |
1068 |
dl |
1.1 |
*/ |
1069 |
jsr166 |
1.158 |
void joinPool(ExecutorService pool) { |
1070 |
dl |
1.1 |
try { |
1071 |
jsr166 |
1.139 |
pool.shutdown(); |
1072 |
dl |
1.274 |
if (!pool.awaitTermination(20 * LONG_DELAY_MS, MILLISECONDS)) { |
1073 |
jsr166 |
1.158 |
try { |
1074 |
|
|
threadFail("ExecutorService " + pool + |
1075 |
|
|
" did not terminate in a timely manner"); |
1076 |
|
|
} finally { |
1077 |
|
|
// last resort, for the benefit of subsequent tests |
1078 |
|
|
pool.shutdownNow(); |
1079 |
jsr166 |
1.167 |
pool.awaitTermination(MEDIUM_DELAY_MS, MILLISECONDS); |
1080 |
jsr166 |
1.158 |
} |
1081 |
|
|
} |
1082 |
jsr166 |
1.33 |
} catch (SecurityException ok) { |
1083 |
dl |
1.22 |
// Allowed in case test doesn't have privs |
1084 |
jsr166 |
1.128 |
} catch (InterruptedException fail) { |
1085 |
jsr166 |
1.158 |
threadFail("Unexpected InterruptedException"); |
1086 |
dl |
1.1 |
} |
1087 |
|
|
} |
1088 |
|
|
|
1089 |
jsr166 |
1.197 |
/** |
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 |
jsr166 |
1.141 |
interface Action { public void run() throws Throwable; } |
1095 |
jsr166 |
1.139 |
|
1096 |
|
|
/** |
1097 |
jsr166 |
1.141 |
* Runs all the given actions in parallel, failing if any fail. |
1098 |
jsr166 |
1.139 |
* Useful for running multiple variants of tests that are |
1099 |
|
|
* necessarily individually slow because they must block. |
1100 |
|
|
*/ |
1101 |
jsr166 |
1.141 |
void testInParallel(Action ... actions) { |
1102 |
jsr166 |
1.160 |
ExecutorService pool = Executors.newCachedThreadPool(); |
1103 |
|
|
try (PoolCleaner cleaner = cleaner(pool)) { |
1104 |
jsr166 |
1.141 |
ArrayList<Future<?>> futures = new ArrayList<>(actions.length); |
1105 |
|
|
for (final Action action : actions) |
1106 |
jsr166 |
1.139 |
futures.add(pool.submit(new CheckedRunnable() { |
1107 |
jsr166 |
1.141 |
public void realRun() throws Throwable { action.run();}})); |
1108 |
jsr166 |
1.139 |
for (Future<?> future : futures) |
1109 |
|
|
try { |
1110 |
|
|
assertNull(future.get(LONG_DELAY_MS, MILLISECONDS)); |
1111 |
|
|
} catch (ExecutionException ex) { |
1112 |
|
|
threadUnexpectedException(ex.getCause()); |
1113 |
|
|
} catch (Exception ex) { |
1114 |
|
|
threadUnexpectedException(ex); |
1115 |
|
|
} |
1116 |
|
|
} |
1117 |
|
|
} |
1118 |
|
|
|
1119 |
jsr166 |
1.266 |
/** 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 |
jsr166 |
1.78 |
/** |
1153 |
jsr166 |
1.156 |
* A debugging tool to print stack traces of most threads, as jstack does. |
1154 |
jsr166 |
1.150 |
* Uninteresting threads are filtered out. |
1155 |
jsr166 |
1.95 |
*/ |
1156 |
dl |
1.274 |
@SuppressWarnings("removal") |
1157 |
jsr166 |
1.156 |
static void dumpTestThreads() { |
1158 |
jsr166 |
1.195 |
SecurityManager sm = System.getSecurityManager(); |
1159 |
|
|
if (sm != null) { |
1160 |
|
|
try { |
1161 |
|
|
System.setSecurityManager(null); |
1162 |
|
|
} catch (SecurityException giveUp) { |
1163 |
|
|
return; |
1164 |
|
|
} |
1165 |
|
|
} |
1166 |
|
|
|
1167 |
jsr166 |
1.150 |
System.err.println("------ stacktrace dump start ------"); |
1168 |
jsr166 |
1.268 |
for (ThreadInfo info : THREAD_MXBEAN.dumpAllThreads(true, true)) |
1169 |
jsr166 |
1.266 |
if (threadOfInterest(info)) |
1170 |
|
|
System.err.print(info); |
1171 |
jsr166 |
1.150 |
System.err.println("------ stacktrace dump end ------"); |
1172 |
jsr166 |
1.195 |
|
1173 |
|
|
if (sm != null) System.setSecurityManager(sm); |
1174 |
jsr166 |
1.95 |
} |
1175 |
|
|
|
1176 |
|
|
/** |
1177 |
jsr166 |
1.224 |
* Checks that thread eventually enters the expected blocked thread state. |
1178 |
|
|
*/ |
1179 |
|
|
void assertThreadBlocks(Thread thread, Thread.State expected) { |
1180 |
jsr166 |
1.228 |
// always sleep at least 1 ms, with high probability avoiding |
1181 |
|
|
// transitory states |
1182 |
jsr166 |
1.225 |
for (long retries = LONG_DELAY_MS * 3 / 4; retries-->0; ) { |
1183 |
jsr166 |
1.224 |
try { delay(1); } |
1184 |
|
|
catch (InterruptedException fail) { |
1185 |
jsr166 |
1.240 |
throw new AssertionError("Unexpected InterruptedException", fail); |
1186 |
jsr166 |
1.224 |
} |
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 |
jsr166 |
1.268 |
* Returns the thread's blocker's class name, if any, else null. |
1198 |
|
|
*/ |
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 |
jsr166 |
1.83 |
* Checks that future.get times out, with the default timeout of |
1209 |
|
|
* {@code timeoutMillis()}. |
1210 |
|
|
*/ |
1211 |
dl |
1.272 |
void assertFutureTimesOut(Future<?> future) { |
1212 |
jsr166 |
1.83 |
assertFutureTimesOut(future, timeoutMillis()); |
1213 |
|
|
} |
1214 |
|
|
|
1215 |
|
|
/** |
1216 |
|
|
* Checks that future.get times out, with the given millisecond timeout. |
1217 |
|
|
*/ |
1218 |
dl |
1.272 |
void assertFutureTimesOut(Future<?> future, long timeoutMillis) { |
1219 |
jsr166 |
1.83 |
long startTime = System.nanoTime(); |
1220 |
|
|
try { |
1221 |
|
|
future.get(timeoutMillis, MILLISECONDS); |
1222 |
|
|
shouldThrow(); |
1223 |
|
|
} catch (TimeoutException success) { |
1224 |
jsr166 |
1.128 |
} catch (Exception fail) { |
1225 |
|
|
threadUnexpectedException(fail); |
1226 |
jsr166 |
1.271 |
} |
1227 |
jsr166 |
1.83 |
assertTrue(millisElapsedSince(startTime) >= timeoutMillis); |
1228 |
jsr166 |
1.271 |
assertFalse(future.isDone()); |
1229 |
jsr166 |
1.83 |
} |
1230 |
|
|
|
1231 |
|
|
/** |
1232 |
jsr166 |
1.53 |
* Fails with message "should throw exception". |
1233 |
jsr166 |
1.27 |
*/ |
1234 |
dl |
1.3 |
public void shouldThrow() { |
1235 |
|
|
fail("Should throw exception"); |
1236 |
|
|
} |
1237 |
|
|
|
1238 |
dl |
1.5 |
/** |
1239 |
jsr166 |
1.53 |
* Fails with message "should throw " + exceptionName. |
1240 |
jsr166 |
1.40 |
*/ |
1241 |
|
|
public void shouldThrow(String exceptionName) { |
1242 |
|
|
fail("Should throw " + exceptionName); |
1243 |
|
|
} |
1244 |
|
|
|
1245 |
|
|
/** |
1246 |
jsr166 |
1.222 |
* The maximum number of consecutive spurious wakeups we should |
1247 |
|
|
* tolerate (from APIs like LockSupport.park) before failing a test. |
1248 |
|
|
*/ |
1249 |
|
|
static final int MAX_SPURIOUS_WAKEUPS = 10; |
1250 |
|
|
|
1251 |
|
|
/** |
1252 |
dl |
1.1 |
* The number of elements to place in collections, arrays, etc. |
1253 |
dl |
1.272 |
* Must be at least ten; |
1254 |
dl |
1.1 |
*/ |
1255 |
dl |
1.272 |
public static final int SIZE = 32; |
1256 |
dl |
1.1 |
|
1257 |
dl |
1.272 |
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 |
dl |
1.274 |
assertFalse(c.remove(itemFor(i))); |
1366 |
dl |
1.272 |
} |
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 |
dl |
1.7 |
|
1383 |
|
|
/** |
1384 |
jsr166 |
1.49 |
* Runs Runnable r with a security policy that permits precisely |
1385 |
|
|
* the specified permissions. If there is no current security |
1386 |
|
|
* manager, the runnable is run twice, both with and without a |
1387 |
|
|
* security manager. We require that any security manager permit |
1388 |
|
|
* getPolicy/setPolicy. |
1389 |
|
|
*/ |
1390 |
dl |
1.274 |
@SuppressWarnings("removal") |
1391 |
jsr166 |
1.49 |
public void runWithPermissions(Runnable r, Permission... permissions) { |
1392 |
|
|
SecurityManager sm = System.getSecurityManager(); |
1393 |
|
|
if (sm == null) { |
1394 |
|
|
r.run(); |
1395 |
jsr166 |
1.93 |
} |
1396 |
|
|
runWithSecurityManagerWithPermissions(r, permissions); |
1397 |
|
|
} |
1398 |
|
|
|
1399 |
|
|
/** |
1400 |
|
|
* Runs Runnable r with a security policy that permits precisely |
1401 |
|
|
* the specified permissions. If there is no current security |
1402 |
|
|
* manager, a temporary one is set for the duration of the |
1403 |
|
|
* Runnable. We require that any security manager permit |
1404 |
|
|
* getPolicy/setPolicy. |
1405 |
|
|
*/ |
1406 |
dl |
1.274 |
@SuppressWarnings("removal") |
1407 |
jsr166 |
1.93 |
public void runWithSecurityManagerWithPermissions(Runnable r, |
1408 |
|
|
Permission... permissions) { |
1409 |
dl |
1.274 |
if (!useSecurityManager) return; |
1410 |
jsr166 |
1.93 |
SecurityManager sm = System.getSecurityManager(); |
1411 |
|
|
if (sm == null) { |
1412 |
jsr166 |
1.49 |
Policy savedPolicy = Policy.getPolicy(); |
1413 |
|
|
try { |
1414 |
|
|
Policy.setPolicy(permissivePolicy()); |
1415 |
|
|
System.setSecurityManager(new SecurityManager()); |
1416 |
jsr166 |
1.93 |
runWithSecurityManagerWithPermissions(r, permissions); |
1417 |
dl |
1.275 |
} catch (UnsupportedOperationException ok) { |
1418 |
jsr166 |
1.49 |
} finally { |
1419 |
dl |
1.275 |
try { |
1420 |
|
|
System.setSecurityManager(null); |
1421 |
|
|
Policy.setPolicy(savedPolicy); |
1422 |
|
|
} catch (Exception ok) { |
1423 |
|
|
} |
1424 |
jsr166 |
1.49 |
} |
1425 |
|
|
} else { |
1426 |
|
|
Policy savedPolicy = Policy.getPolicy(); |
1427 |
|
|
AdjustablePolicy policy = new AdjustablePolicy(permissions); |
1428 |
|
|
Policy.setPolicy(policy); |
1429 |
|
|
|
1430 |
|
|
try { |
1431 |
|
|
r.run(); |
1432 |
|
|
} finally { |
1433 |
|
|
policy.addPermission(new SecurityPermission("setPolicy")); |
1434 |
|
|
Policy.setPolicy(savedPolicy); |
1435 |
|
|
} |
1436 |
|
|
} |
1437 |
|
|
} |
1438 |
|
|
|
1439 |
|
|
/** |
1440 |
|
|
* Runs a runnable without any permissions. |
1441 |
|
|
*/ |
1442 |
|
|
public void runWithoutPermissions(Runnable r) { |
1443 |
|
|
runWithPermissions(r); |
1444 |
|
|
} |
1445 |
|
|
|
1446 |
|
|
/** |
1447 |
dl |
1.7 |
* A security policy where new permissions can be dynamically added |
1448 |
|
|
* or all cleared. |
1449 |
|
|
*/ |
1450 |
dl |
1.274 |
@SuppressWarnings("removal") |
1451 |
jsr166 |
1.45 |
public static class AdjustablePolicy extends java.security.Policy { |
1452 |
dl |
1.7 |
Permissions perms = new Permissions(); |
1453 |
jsr166 |
1.49 |
AdjustablePolicy(Permission... permissions) { |
1454 |
|
|
for (Permission permission : permissions) |
1455 |
|
|
perms.add(permission); |
1456 |
|
|
} |
1457 |
dl |
1.7 |
void addPermission(Permission perm) { perms.add(perm); } |
1458 |
|
|
void clearPermissions() { perms = new Permissions(); } |
1459 |
jsr166 |
1.42 |
public PermissionCollection getPermissions(CodeSource cs) { |
1460 |
|
|
return perms; |
1461 |
|
|
} |
1462 |
|
|
public PermissionCollection getPermissions(ProtectionDomain pd) { |
1463 |
|
|
return perms; |
1464 |
|
|
} |
1465 |
|
|
public boolean implies(ProtectionDomain pd, Permission p) { |
1466 |
|
|
return perms.implies(p); |
1467 |
|
|
} |
1468 |
|
|
public void refresh() {} |
1469 |
jsr166 |
1.93 |
public String toString() { |
1470 |
jsr166 |
1.216 |
List<Permission> ps = new ArrayList<>(); |
1471 |
jsr166 |
1.93 |
for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();) |
1472 |
|
|
ps.add(e.nextElement()); |
1473 |
|
|
return "AdjustablePolicy with permissions " + ps; |
1474 |
|
|
} |
1475 |
dl |
1.7 |
} |
1476 |
dl |
1.1 |
|
1477 |
jsr166 |
1.38 |
/** |
1478 |
jsr166 |
1.49 |
* Returns a policy containing all the permissions we ever need. |
1479 |
|
|
*/ |
1480 |
dl |
1.274 |
@SuppressWarnings("removal") |
1481 |
jsr166 |
1.49 |
public static Policy permissivePolicy() { |
1482 |
|
|
return new AdjustablePolicy |
1483 |
|
|
// Permissions j.u.c. needs directly |
1484 |
|
|
(new RuntimePermission("modifyThread"), |
1485 |
|
|
new RuntimePermission("getClassLoader"), |
1486 |
|
|
new RuntimePermission("setContextClassLoader"), |
1487 |
|
|
// Permissions needed to change permissions! |
1488 |
|
|
new SecurityPermission("getPolicy"), |
1489 |
|
|
new SecurityPermission("setPolicy"), |
1490 |
|
|
new RuntimePermission("setSecurityManager"), |
1491 |
|
|
// Permissions needed by the junit test harness |
1492 |
|
|
new RuntimePermission("accessDeclaredMembers"), |
1493 |
|
|
new PropertyPermission("*", "read"), |
1494 |
|
|
new java.io.FilePermission("<<ALL FILES>>", "read")); |
1495 |
|
|
} |
1496 |
|
|
|
1497 |
|
|
/** |
1498 |
jsr166 |
1.60 |
* Sleeps until the given time has elapsed. |
1499 |
jsr166 |
1.239 |
* Throws AssertionError if interrupted. |
1500 |
jsr166 |
1.60 |
*/ |
1501 |
jsr166 |
1.201 |
static void sleep(long millis) { |
1502 |
jsr166 |
1.60 |
try { |
1503 |
dl |
1.76 |
delay(millis); |
1504 |
jsr166 |
1.128 |
} catch (InterruptedException fail) { |
1505 |
jsr166 |
1.239 |
throw new AssertionError("Unexpected InterruptedException", fail); |
1506 |
jsr166 |
1.60 |
} |
1507 |
|
|
} |
1508 |
|
|
|
1509 |
|
|
/** |
1510 |
jsr166 |
1.88 |
* Spin-waits up to the specified number of milliseconds for the given |
1511 |
jsr166 |
1.65 |
* thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING. |
1512 |
jsr166 |
1.248 |
* @param waitingForGodot if non-null, an additional condition to satisfy |
1513 |
jsr166 |
1.65 |
*/ |
1514 |
jsr166 |
1.248 |
void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis, |
1515 |
|
|
Callable<Boolean> waitingForGodot) { |
1516 |
|
|
for (long startTime = 0L;;) { |
1517 |
|
|
switch (thread.getState()) { |
1518 |
jsr166 |
1.250 |
default: break; |
1519 |
jsr166 |
1.248 |
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 |
jsr166 |
1.67 |
fail("Unexpected thread termination"); |
1527 |
jsr166 |
1.248 |
} |
1528 |
|
|
|
1529 |
|
|
if (startTime == 0L) |
1530 |
jsr166 |
1.199 |
startTime = System.nanoTime(); |
1531 |
jsr166 |
1.88 |
else if (millisElapsedSince(startTime) > timeoutMillis) { |
1532 |
jsr166 |
1.248 |
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 |
jsr166 |
1.67 |
} |
1540 |
jsr166 |
1.65 |
Thread.yield(); |
1541 |
|
|
} |
1542 |
|
|
} |
1543 |
|
|
|
1544 |
|
|
/** |
1545 |
jsr166 |
1.219 |
* Spin-waits up to the specified number of milliseconds for the given |
1546 |
jsr166 |
1.248 |
* thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING. |
1547 |
jsr166 |
1.219 |
*/ |
1548 |
jsr166 |
1.248 |
void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) { |
1549 |
|
|
waitForThreadToEnterWaitState(thread, timeoutMillis, null); |
1550 |
jsr166 |
1.219 |
} |
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 |
jsr166 |
1.75 |
*/ |
1556 |
|
|
void waitForThreadToEnterWaitState(Thread thread) { |
1557 |
jsr166 |
1.248 |
waitForThreadToEnterWaitState(thread, LONG_DELAY_MS, null); |
1558 |
jsr166 |
1.75 |
} |
1559 |
|
|
|
1560 |
|
|
/** |
1561 |
jsr166 |
1.219 |
* 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 |
jsr166 |
1.248 |
void waitForThreadToEnterWaitState(Thread thread, |
1566 |
|
|
Callable<Boolean> waitingForGodot) { |
1567 |
jsr166 |
1.219 |
waitForThreadToEnterWaitState(thread, LONG_DELAY_MS, waitingForGodot); |
1568 |
|
|
} |
1569 |
|
|
|
1570 |
|
|
/** |
1571 |
jsr166 |
1.257 |
* 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 |
|
|
/** |
1585 |
jsr166 |
1.66 |
* Returns the number of milliseconds since time given by |
1586 |
|
|
* startNanoTime, which must have been previously returned from a |
1587 |
jsr166 |
1.124 |
* call to {@link System#nanoTime()}. |
1588 |
jsr166 |
1.66 |
*/ |
1589 |
jsr166 |
1.117 |
static long millisElapsedSince(long startNanoTime) { |
1590 |
jsr166 |
1.66 |
return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime); |
1591 |
|
|
} |
1592 |
jsr166 |
1.68 |
|
1593 |
jsr166 |
1.120 |
/** |
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 |
jsr166 |
1.245 |
T actual = null; |
1600 |
jsr166 |
1.120 |
try { |
1601 |
jsr166 |
1.245 |
actual = f.get(timeoutMillis, MILLISECONDS); |
1602 |
jsr166 |
1.120 |
} catch (Throwable fail) { threadUnexpectedException(fail); } |
1603 |
jsr166 |
1.245 |
assertEquals(expectedValue, actual); |
1604 |
jsr166 |
1.120 |
if (millisElapsedSince(startTime) > timeoutMillis/2) |
1605 |
jsr166 |
1.239 |
throw new AssertionError("timed get did not return promptly"); |
1606 |
jsr166 |
1.120 |
} |
1607 |
|
|
|
1608 |
|
|
<T> void checkTimedGet(Future<T> f, T expectedValue) { |
1609 |
|
|
checkTimedGet(f, expectedValue, LONG_DELAY_MS); |
1610 |
|
|
} |
1611 |
|
|
|
1612 |
jsr166 |
1.66 |
/** |
1613 |
jsr166 |
1.58 |
* Returns a new started daemon Thread running the given runnable. |
1614 |
jsr166 |
1.38 |
*/ |
1615 |
|
|
Thread newStartedThread(Runnable runnable) { |
1616 |
|
|
Thread t = new Thread(runnable); |
1617 |
jsr166 |
1.58 |
t.setDaemon(true); |
1618 |
jsr166 |
1.38 |
t.start(); |
1619 |
|
|
return t; |
1620 |
|
|
} |
1621 |
dl |
1.1 |
|
1622 |
jsr166 |
1.59 |
/** |
1623 |
jsr166 |
1.268 |
* Returns a new started daemon Thread running the given action, |
1624 |
|
|
* wrapped in a CheckedRunnable. |
1625 |
|
|
*/ |
1626 |
|
|
Thread newStartedThread(Action action) { |
1627 |
jsr166 |
1.269 |
return newStartedThread(checkedRunnable(action)); |
1628 |
jsr166 |
1.268 |
} |
1629 |
|
|
|
1630 |
|
|
/** |
1631 |
jsr166 |
1.59 |
* 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 |
jsr166 |
1.261 |
void awaitTermination(Thread thread, long timeoutMillis) { |
1636 |
jsr166 |
1.59 |
try { |
1637 |
jsr166 |
1.261 |
thread.join(timeoutMillis); |
1638 |
jsr166 |
1.128 |
} catch (InterruptedException fail) { |
1639 |
|
|
threadUnexpectedException(fail); |
1640 |
jsr166 |
1.258 |
} |
1641 |
jsr166 |
1.261 |
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 |
jsr166 |
1.262 |
// Interrupt thread __after__ having reported its stack trace |
1649 |
jsr166 |
1.261 |
thread.interrupt(); |
1650 |
|
|
} |
1651 |
jsr166 |
1.59 |
} |
1652 |
|
|
} |
1653 |
|
|
|
1654 |
jsr166 |
1.75 |
/** |
1655 |
|
|
* Waits for LONG_DELAY_MS milliseconds for the thread to |
1656 |
|
|
* terminate (using {@link Thread#join(long)}), else interrupts |
1657 |
|
|
* the thread (in the hope that it may terminate later) and fails. |
1658 |
|
|
*/ |
1659 |
|
|
void awaitTermination(Thread t) { |
1660 |
|
|
awaitTermination(t, LONG_DELAY_MS); |
1661 |
|
|
} |
1662 |
|
|
|
1663 |
dl |
1.1 |
// Some convenient Runnable classes |
1664 |
|
|
|
1665 |
jsr166 |
1.45 |
public abstract class CheckedRunnable implements Runnable { |
1666 |
|
|
protected abstract void realRun() throws Throwable; |
1667 |
jsr166 |
1.35 |
|
1668 |
|
|
public final void run() { |
1669 |
|
|
try { |
1670 |
|
|
realRun(); |
1671 |
jsr166 |
1.128 |
} catch (Throwable fail) { |
1672 |
|
|
threadUnexpectedException(fail); |
1673 |
jsr166 |
1.35 |
} |
1674 |
|
|
} |
1675 |
|
|
} |
1676 |
|
|
|
1677 |
jsr166 |
1.268 |
Runnable checkedRunnable(Action action) { |
1678 |
|
|
return new CheckedRunnable() { |
1679 |
|
|
public void realRun() throws Throwable { |
1680 |
|
|
action.run(); |
1681 |
|
|
}}; |
1682 |
|
|
} |
1683 |
|
|
|
1684 |
jsr166 |
1.45 |
public abstract class ThreadShouldThrow extends Thread { |
1685 |
|
|
protected abstract void realRun() throws Throwable; |
1686 |
jsr166 |
1.40 |
|
1687 |
|
|
final Class<?> exceptionClass; |
1688 |
|
|
|
1689 |
|
|
<T extends Throwable> ThreadShouldThrow(Class<T> exceptionClass) { |
1690 |
|
|
this.exceptionClass = exceptionClass; |
1691 |
|
|
} |
1692 |
|
|
|
1693 |
|
|
public final void run() { |
1694 |
|
|
try { |
1695 |
|
|
realRun(); |
1696 |
|
|
} catch (Throwable t) { |
1697 |
|
|
if (! exceptionClass.isInstance(t)) |
1698 |
|
|
threadUnexpectedException(t); |
1699 |
jsr166 |
1.248 |
return; |
1700 |
jsr166 |
1.40 |
} |
1701 |
jsr166 |
1.248 |
threadShouldThrow(exceptionClass.getSimpleName()); |
1702 |
jsr166 |
1.40 |
} |
1703 |
|
|
} |
1704 |
|
|
|
1705 |
jsr166 |
1.45 |
public abstract class CheckedInterruptedRunnable implements Runnable { |
1706 |
|
|
protected abstract void realRun() throws Throwable; |
1707 |
jsr166 |
1.35 |
|
1708 |
|
|
public final void run() { |
1709 |
|
|
try { |
1710 |
|
|
realRun(); |
1711 |
|
|
} catch (InterruptedException success) { |
1712 |
jsr166 |
1.81 |
threadAssertFalse(Thread.interrupted()); |
1713 |
jsr166 |
1.248 |
return; |
1714 |
jsr166 |
1.128 |
} catch (Throwable fail) { |
1715 |
|
|
threadUnexpectedException(fail); |
1716 |
jsr166 |
1.35 |
} |
1717 |
jsr166 |
1.248 |
threadShouldThrow("InterruptedException"); |
1718 |
jsr166 |
1.35 |
} |
1719 |
|
|
} |
1720 |
|
|
|
1721 |
jsr166 |
1.45 |
public abstract class CheckedCallable<T> implements Callable<T> { |
1722 |
|
|
protected abstract T realCall() throws Throwable; |
1723 |
jsr166 |
1.35 |
|
1724 |
|
|
public final T call() { |
1725 |
|
|
try { |
1726 |
|
|
return realCall(); |
1727 |
jsr166 |
1.128 |
} catch (Throwable fail) { |
1728 |
|
|
threadUnexpectedException(fail); |
1729 |
jsr166 |
1.40 |
} |
1730 |
jsr166 |
1.248 |
throw new AssertionError("unreached"); |
1731 |
jsr166 |
1.35 |
} |
1732 |
|
|
} |
1733 |
|
|
|
1734 |
jsr166 |
1.45 |
public static class NoOpRunnable implements Runnable { |
1735 |
dl |
1.1 |
public void run() {} |
1736 |
|
|
} |
1737 |
|
|
|
1738 |
dl |
1.272 |
public static class NoOpCallable implements Callable<Object> { |
1739 |
dl |
1.1 |
public Object call() { return Boolean.TRUE; } |
1740 |
dl |
1.10 |
} |
1741 |
|
|
|
1742 |
jsr166 |
1.45 |
public static final String TEST_STRING = "a test string"; |
1743 |
dl |
1.10 |
|
1744 |
jsr166 |
1.45 |
public static class StringTask implements Callable<String> { |
1745 |
jsr166 |
1.144 |
final String value; |
1746 |
|
|
public StringTask() { this(TEST_STRING); } |
1747 |
|
|
public StringTask(String value) { this.value = value; } |
1748 |
|
|
public String call() { return value; } |
1749 |
dl |
1.10 |
} |
1750 |
|
|
|
1751 |
jsr166 |
1.48 |
public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) { |
1752 |
|
|
return new CheckedCallable<String>() { |
1753 |
jsr166 |
1.64 |
protected String realCall() { |
1754 |
jsr166 |
1.48 |
try { |
1755 |
|
|
latch.await(); |
1756 |
|
|
} catch (InterruptedException quittingTime) {} |
1757 |
|
|
return TEST_STRING; |
1758 |
|
|
}}; |
1759 |
|
|
} |
1760 |
|
|
|
1761 |
jsr166 |
1.148 |
public Runnable countDowner(final CountDownLatch latch) { |
1762 |
|
|
return new CheckedRunnable() { |
1763 |
|
|
public void realRun() throws InterruptedException { |
1764 |
|
|
latch.countDown(); |
1765 |
|
|
}}; |
1766 |
|
|
} |
1767 |
|
|
|
1768 |
jsr166 |
1.161 |
class LatchAwaiter extends CheckedRunnable { |
1769 |
jsr166 |
1.162 |
static final int NEW = 0; |
1770 |
|
|
static final int RUNNING = 1; |
1771 |
|
|
static final int DONE = 2; |
1772 |
jsr166 |
1.161 |
final CountDownLatch latch; |
1773 |
|
|
int state = NEW; |
1774 |
|
|
LatchAwaiter(CountDownLatch latch) { this.latch = latch; } |
1775 |
|
|
public void realRun() throws InterruptedException { |
1776 |
|
|
state = 1; |
1777 |
|
|
await(latch); |
1778 |
|
|
state = 2; |
1779 |
|
|
} |
1780 |
|
|
} |
1781 |
jsr166 |
1.162 |
|
1782 |
jsr166 |
1.161 |
public LatchAwaiter awaiter(CountDownLatch latch) { |
1783 |
|
|
return new LatchAwaiter(latch); |
1784 |
jsr166 |
1.73 |
} |
1785 |
|
|
|
1786 |
jsr166 |
1.188 |
public void await(CountDownLatch latch, long timeoutMillis) { |
1787 |
jsr166 |
1.246 |
boolean timedOut = false; |
1788 |
jsr166 |
1.79 |
try { |
1789 |
jsr166 |
1.246 |
timedOut = !latch.await(timeoutMillis, MILLISECONDS); |
1790 |
jsr166 |
1.128 |
} catch (Throwable fail) { |
1791 |
|
|
threadUnexpectedException(fail); |
1792 |
jsr166 |
1.79 |
} |
1793 |
jsr166 |
1.246 |
if (timedOut) |
1794 |
|
|
fail("timed out waiting for CountDownLatch for " |
1795 |
|
|
+ (timeoutMillis/1000) + " sec"); |
1796 |
jsr166 |
1.79 |
} |
1797 |
|
|
|
1798 |
jsr166 |
1.188 |
public void await(CountDownLatch latch) { |
1799 |
|
|
await(latch, LONG_DELAY_MS); |
1800 |
|
|
} |
1801 |
|
|
|
1802 |
jsr166 |
1.89 |
public void await(Semaphore semaphore) { |
1803 |
jsr166 |
1.246 |
boolean timedOut = false; |
1804 |
jsr166 |
1.89 |
try { |
1805 |
jsr166 |
1.246 |
timedOut = !semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS); |
1806 |
jsr166 |
1.128 |
} catch (Throwable fail) { |
1807 |
|
|
threadUnexpectedException(fail); |
1808 |
jsr166 |
1.89 |
} |
1809 |
jsr166 |
1.246 |
if (timedOut) |
1810 |
|
|
fail("timed out waiting for Semaphore for " |
1811 |
|
|
+ (LONG_DELAY_MS/1000) + " sec"); |
1812 |
jsr166 |
1.89 |
} |
1813 |
|
|
|
1814 |
jsr166 |
1.226 |
public void await(CyclicBarrier barrier) { |
1815 |
|
|
try { |
1816 |
|
|
barrier.await(LONG_DELAY_MS, MILLISECONDS); |
1817 |
|
|
} catch (Throwable fail) { |
1818 |
|
|
threadUnexpectedException(fail); |
1819 |
|
|
} |
1820 |
|
|
} |
1821 |
|
|
|
1822 |
jsr166 |
1.81 |
// /** |
1823 |
|
|
// * Spin-waits up to LONG_DELAY_MS until flag becomes true. |
1824 |
|
|
// */ |
1825 |
|
|
// public void await(AtomicBoolean flag) { |
1826 |
|
|
// await(flag, LONG_DELAY_MS); |
1827 |
|
|
// } |
1828 |
|
|
|
1829 |
|
|
// /** |
1830 |
|
|
// * Spin-waits up to the specified timeout until flag becomes true. |
1831 |
|
|
// */ |
1832 |
|
|
// public void await(AtomicBoolean flag, long timeoutMillis) { |
1833 |
|
|
// long startTime = System.nanoTime(); |
1834 |
|
|
// while (!flag.get()) { |
1835 |
|
|
// if (millisElapsedSince(startTime) > timeoutMillis) |
1836 |
jsr166 |
1.239 |
// throw new AssertionError("timed out"); |
1837 |
jsr166 |
1.81 |
// Thread.yield(); |
1838 |
|
|
// } |
1839 |
|
|
// } |
1840 |
|
|
|
1841 |
jsr166 |
1.45 |
public static class NPETask implements Callable<String> { |
1842 |
dl |
1.10 |
public String call() { throw new NullPointerException(); } |
1843 |
|
|
} |
1844 |
|
|
|
1845 |
jsr166 |
1.63 |
public Runnable possiblyInterruptedRunnable(final long timeoutMillis) { |
1846 |
|
|
return new CheckedRunnable() { |
1847 |
|
|
protected void realRun() { |
1848 |
|
|
try { |
1849 |
dl |
1.76 |
delay(timeoutMillis); |
1850 |
jsr166 |
1.63 |
} catch (InterruptedException ok) {} |
1851 |
|
|
}}; |
1852 |
|
|
} |
1853 |
|
|
|
1854 |
dl |
1.5 |
/** |
1855 |
|
|
* For use as ThreadFactory in constructors |
1856 |
|
|
*/ |
1857 |
jsr166 |
1.45 |
public static class SimpleThreadFactory implements ThreadFactory { |
1858 |
jsr166 |
1.33 |
public Thread newThread(Runnable r) { |
1859 |
dl |
1.5 |
return new Thread(r); |
1860 |
jsr166 |
1.27 |
} |
1861 |
dl |
1.5 |
} |
1862 |
|
|
|
1863 |
jsr166 |
1.61 |
public interface TrackedRunnable extends Runnable { |
1864 |
|
|
boolean isDone(); |
1865 |
|
|
} |
1866 |
|
|
|
1867 |
jsr166 |
1.45 |
public static class TrackedNoOpRunnable implements Runnable { |
1868 |
|
|
public volatile boolean done = false; |
1869 |
dl |
1.6 |
public void run() { |
1870 |
|
|
done = true; |
1871 |
dl |
1.5 |
} |
1872 |
|
|
} |
1873 |
|
|
|
1874 |
jsr166 |
1.53 |
/** |
1875 |
|
|
* Analog of CheckedRunnable for RecursiveAction |
1876 |
|
|
*/ |
1877 |
|
|
public abstract class CheckedRecursiveAction extends RecursiveAction { |
1878 |
|
|
protected abstract void realCompute() throws Throwable; |
1879 |
|
|
|
1880 |
jsr166 |
1.108 |
@Override protected final void compute() { |
1881 |
jsr166 |
1.53 |
try { |
1882 |
|
|
realCompute(); |
1883 |
jsr166 |
1.128 |
} catch (Throwable fail) { |
1884 |
|
|
threadUnexpectedException(fail); |
1885 |
jsr166 |
1.53 |
} |
1886 |
|
|
} |
1887 |
|
|
} |
1888 |
|
|
|
1889 |
|
|
/** |
1890 |
|
|
* Analog of CheckedCallable for RecursiveTask |
1891 |
|
|
*/ |
1892 |
|
|
public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> { |
1893 |
|
|
protected abstract T realCompute() throws Throwable; |
1894 |
|
|
|
1895 |
jsr166 |
1.108 |
@Override protected final T compute() { |
1896 |
jsr166 |
1.53 |
try { |
1897 |
|
|
return realCompute(); |
1898 |
jsr166 |
1.128 |
} catch (Throwable fail) { |
1899 |
|
|
threadUnexpectedException(fail); |
1900 |
jsr166 |
1.53 |
} |
1901 |
jsr166 |
1.248 |
throw new AssertionError("unreached"); |
1902 |
jsr166 |
1.53 |
} |
1903 |
|
|
} |
1904 |
dl |
1.5 |
|
1905 |
|
|
/** |
1906 |
|
|
* For use as RejectedExecutionHandler in constructors |
1907 |
|
|
*/ |
1908 |
jsr166 |
1.45 |
public static class NoOpREHandler implements RejectedExecutionHandler { |
1909 |
jsr166 |
1.35 |
public void rejectedExecution(Runnable r, |
1910 |
|
|
ThreadPoolExecutor executor) {} |
1911 |
dl |
1.5 |
} |
1912 |
jsr166 |
1.27 |
|
1913 |
jsr166 |
1.60 |
/** |
1914 |
jsr166 |
1.86 |
* A CyclicBarrier that uses timed await and fails with |
1915 |
jsr166 |
1.239 |
* AssertionErrors instead of throwing checked exceptions. |
1916 |
jsr166 |
1.60 |
*/ |
1917 |
jsr166 |
1.202 |
public static class CheckedBarrier extends CyclicBarrier { |
1918 |
jsr166 |
1.60 |
public CheckedBarrier(int parties) { super(parties); } |
1919 |
|
|
|
1920 |
|
|
public int await() { |
1921 |
|
|
try { |
1922 |
jsr166 |
1.270 |
return super.await(LONGER_DELAY_MS, MILLISECONDS); |
1923 |
jsr166 |
1.128 |
} catch (TimeoutException timedOut) { |
1924 |
jsr166 |
1.239 |
throw new AssertionError("timed out"); |
1925 |
jsr166 |
1.128 |
} catch (Exception fail) { |
1926 |
jsr166 |
1.239 |
throw new AssertionError("Unexpected exception: " + fail, fail); |
1927 |
jsr166 |
1.60 |
} |
1928 |
|
|
} |
1929 |
|
|
} |
1930 |
|
|
|
1931 |
dl |
1.272 |
void checkEmpty(BlockingQueue<?> q) { |
1932 |
jsr166 |
1.72 |
try { |
1933 |
|
|
assertTrue(q.isEmpty()); |
1934 |
|
|
assertEquals(0, q.size()); |
1935 |
|
|
assertNull(q.peek()); |
1936 |
|
|
assertNull(q.poll()); |
1937 |
jsr166 |
1.232 |
assertNull(q.poll(randomExpiredTimeout(), randomTimeUnit())); |
1938 |
jsr166 |
1.72 |
assertEquals(q.toString(), "[]"); |
1939 |
|
|
assertTrue(Arrays.equals(q.toArray(), new Object[0])); |
1940 |
|
|
assertFalse(q.iterator().hasNext()); |
1941 |
|
|
try { |
1942 |
|
|
q.element(); |
1943 |
|
|
shouldThrow(); |
1944 |
|
|
} catch (NoSuchElementException success) {} |
1945 |
|
|
try { |
1946 |
|
|
q.iterator().next(); |
1947 |
|
|
shouldThrow(); |
1948 |
|
|
} catch (NoSuchElementException success) {} |
1949 |
|
|
try { |
1950 |
|
|
q.remove(); |
1951 |
|
|
shouldThrow(); |
1952 |
|
|
} catch (NoSuchElementException success) {} |
1953 |
jsr166 |
1.128 |
} catch (InterruptedException fail) { threadUnexpectedException(fail); } |
1954 |
jsr166 |
1.72 |
} |
1955 |
|
|
|
1956 |
jsr166 |
1.91 |
void assertSerialEquals(Object x, Object y) { |
1957 |
|
|
assertTrue(Arrays.equals(serialBytes(x), serialBytes(y))); |
1958 |
|
|
} |
1959 |
|
|
|
1960 |
|
|
void assertNotSerialEquals(Object x, Object y) { |
1961 |
|
|
assertFalse(Arrays.equals(serialBytes(x), serialBytes(y))); |
1962 |
|
|
} |
1963 |
|
|
|
1964 |
|
|
byte[] serialBytes(Object o) { |
1965 |
jsr166 |
1.79 |
try { |
1966 |
|
|
ByteArrayOutputStream bos = new ByteArrayOutputStream(); |
1967 |
|
|
ObjectOutputStream oos = new ObjectOutputStream(bos); |
1968 |
|
|
oos.writeObject(o); |
1969 |
|
|
oos.flush(); |
1970 |
|
|
oos.close(); |
1971 |
jsr166 |
1.91 |
return bos.toByteArray(); |
1972 |
jsr166 |
1.128 |
} catch (Throwable fail) { |
1973 |
|
|
threadUnexpectedException(fail); |
1974 |
jsr166 |
1.91 |
return new byte[0]; |
1975 |
|
|
} |
1976 |
|
|
} |
1977 |
|
|
|
1978 |
dl |
1.272 |
@SuppressWarnings("unchecked") |
1979 |
jsr166 |
1.253 |
void assertImmutable(Object o) { |
1980 |
jsr166 |
1.208 |
if (o instanceof Collection) { |
1981 |
|
|
assertThrows( |
1982 |
|
|
UnsupportedOperationException.class, |
1983 |
jsr166 |
1.253 |
() -> ((Collection) o).add(null)); |
1984 |
jsr166 |
1.208 |
} |
1985 |
|
|
} |
1986 |
jsr166 |
1.209 |
|
1987 |
jsr166 |
1.91 |
@SuppressWarnings("unchecked") |
1988 |
|
|
<T> T serialClone(T o) { |
1989 |
jsr166 |
1.247 |
T clone = null; |
1990 |
jsr166 |
1.91 |
try { |
1991 |
jsr166 |
1.87 |
ObjectInputStream ois = new ObjectInputStream |
1992 |
jsr166 |
1.91 |
(new ByteArrayInputStream(serialBytes(o))); |
1993 |
jsr166 |
1.247 |
clone = (T) ois.readObject(); |
1994 |
jsr166 |
1.128 |
} catch (Throwable fail) { |
1995 |
|
|
threadUnexpectedException(fail); |
1996 |
jsr166 |
1.79 |
} |
1997 |
jsr166 |
1.247 |
if (o == clone) assertImmutable(o); |
1998 |
|
|
else assertSame(o.getClass(), clone.getClass()); |
1999 |
|
|
return clone; |
2000 |
jsr166 |
1.79 |
} |
2001 |
jsr166 |
1.106 |
|
2002 |
jsr166 |
1.208 |
/** |
2003 |
jsr166 |
1.211 |
* 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 |
jsr166 |
1.247 |
else assertSame(o.getClass(), clone.getClass()); |
2019 |
jsr166 |
1.211 |
return clone; |
2020 |
|
|
} |
2021 |
|
|
|
2022 |
|
|
/** |
2023 |
jsr166 |
1.208 |
* 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 |
jsr166 |
1.106 |
public void assertThrows(Class<? extends Throwable> expectedExceptionClass, |
2043 |
jsr166 |
1.253 |
Action... throwingActions) { |
2044 |
|
|
for (Action throwingAction : throwingActions) { |
2045 |
jsr166 |
1.106 |
boolean threw = false; |
2046 |
|
|
try { throwingAction.run(); } |
2047 |
|
|
catch (Throwable t) { |
2048 |
|
|
threw = true; |
2049 |
jsr166 |
1.239 |
if (!expectedExceptionClass.isInstance(t)) |
2050 |
|
|
throw new AssertionError( |
2051 |
|
|
"Expected " + expectedExceptionClass.getName() + |
2052 |
|
|
", got " + t.getClass().getName(), |
2053 |
|
|
t); |
2054 |
jsr166 |
1.106 |
} |
2055 |
|
|
if (!threw) |
2056 |
|
|
shouldThrow(expectedExceptionClass.getName()); |
2057 |
|
|
} |
2058 |
|
|
} |
2059 |
jsr166 |
1.126 |
|
2060 |
|
|
public void assertIteratorExhausted(Iterator<?> it) { |
2061 |
|
|
try { |
2062 |
|
|
it.next(); |
2063 |
|
|
shouldThrow(); |
2064 |
|
|
} catch (NoSuchElementException success) {} |
2065 |
|
|
assertFalse(it.hasNext()); |
2066 |
jsr166 |
1.127 |
} |
2067 |
jsr166 |
1.191 |
|
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 |
jsr166 |
1.193 |
|
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 |
jsr166 |
1.234 |
static <T> void shuffle(T[] array) { |
2083 |
|
|
Collections.shuffle(Arrays.asList(array), ThreadLocalRandom.current()); |
2084 |
|
|
} |
2085 |
|
|
|
2086 |
jsr166 |
1.236 |
/** |
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 |
jsr166 |
1.234 |
// --- Shared assertions for Executor tests --- |
2099 |
|
|
|
2100 |
jsr166 |
1.233 |
/** |
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 |
jsr166 |
1.234 |
@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 |
dl |
1.272 |
es.submit((Callable<?>) null); |
2129 |
jsr166 |
1.234 |
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 |
dl |
1.272 |
ses.schedule((Callable<?>) null, |
2141 |
jsr166 |
1.234 |
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 |
jsr166 |
1.200 |
} |
2269 |
jsr166 |
1.243 |
|
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 |
dl |
1.272 |
assertEquals(new HashSet<Object>(x), new HashSet<Object>(y)); |
2300 |
jsr166 |
1.243 |
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 |
dl |
1.1 |
} |