ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
(Generate patch)

Comparing jsr166/src/test/tck/JSR166TestCase.java (file contents):
Revision 1.54 by jsr166, Fri Sep 17 00:52:36 2010 UTC vs.
Revision 1.147 by jsr166, Sat Sep 26 19:08:26 2015 UTC

# Line 1 | Line 1
1   /*
2   * Written by Doug Lea with assistance from members of JCP JSR-166
3   * Expert Group and released to the public domain, as explained at
4 < * http://creativecommons.org/licenses/publicdomain
4 > * http://creativecommons.org/publicdomain/zero/1.0/
5   * Other contributors include Andrew Wright, Jeffrey Hayes,
6   * Pat Fisher, Mike Judd.
7   */
8  
9 import junit.framework.*;
10 import java.util.PropertyPermission;
11 import java.util.concurrent.*;
12 import java.util.concurrent.atomic.AtomicReference;
9   import static java.util.concurrent.TimeUnit.MILLISECONDS;
10 + import static java.util.concurrent.TimeUnit.NANOSECONDS;
11 +
12 + import java.io.ByteArrayInputStream;
13 + import java.io.ByteArrayOutputStream;
14 + import java.io.ObjectInputStream;
15 + import java.io.ObjectOutputStream;
16 + import java.lang.management.ManagementFactory;
17 + import java.lang.management.ThreadInfo;
18 + import java.lang.reflect.Constructor;
19 + import java.lang.reflect.Method;
20 + import java.lang.reflect.Modifier;
21   import java.security.CodeSource;
22   import java.security.Permission;
23   import java.security.PermissionCollection;
# Line 18 | Line 25 | import java.security.Permissions;
25   import java.security.Policy;
26   import java.security.ProtectionDomain;
27   import java.security.SecurityPermission;
28 + import java.util.ArrayList;
29 + import java.util.Arrays;
30 + import java.util.Date;
31 + import java.util.Enumeration;
32 + import java.util.Iterator;
33 + import java.util.List;
34 + import java.util.NoSuchElementException;
35 + import java.util.PropertyPermission;
36 + import java.util.concurrent.BlockingQueue;
37 + import java.util.concurrent.Callable;
38 + import java.util.concurrent.CountDownLatch;
39 + import java.util.concurrent.CyclicBarrier;
40 + import java.util.concurrent.ExecutionException;
41 + import java.util.concurrent.Executors;
42 + import java.util.concurrent.ExecutorService;
43 + import java.util.concurrent.ForkJoinPool;
44 + import java.util.concurrent.Future;
45 + import java.util.concurrent.RecursiveAction;
46 + import java.util.concurrent.RecursiveTask;
47 + import java.util.concurrent.RejectedExecutionHandler;
48 + import java.util.concurrent.Semaphore;
49 + import java.util.concurrent.ThreadFactory;
50 + import java.util.concurrent.ThreadPoolExecutor;
51 + import java.util.concurrent.TimeoutException;
52 + import java.util.concurrent.atomic.AtomicReference;
53 + import java.util.regex.Pattern;
54 +
55 + import junit.framework.AssertionFailedError;
56 + import junit.framework.Test;
57 + import junit.framework.TestCase;
58 + import junit.framework.TestResult;
59 + import junit.framework.TestSuite;
60  
61   /**
62   * Base class for JSR166 Junit TCK tests.  Defines some constants,
# Line 29 | Line 68 | import java.security.SecurityPermission;
68   *
69   * <ol>
70   *
71 < * <li> All assertions in code running in generated threads must use
71 > * <li>All assertions in code running in generated threads must use
72   * the forms {@link #threadFail}, {@link #threadAssertTrue}, {@link
73   * #threadAssertEquals}, or {@link #threadAssertNull}, (not
74   * {@code fail}, {@code assertTrue}, etc.) It is OK (but not
75   * particularly recommended) for other code to use these forms too.
76   * Only the most typically used JUnit assertion methods are defined
77 < * this way, but enough to live with.</li>
77 > * this way, but enough to live with.
78   *
79 < * <li> If you override {@link #setUp} or {@link #tearDown}, make sure
79 > * <li>If you override {@link #setUp} or {@link #tearDown}, make sure
80   * to invoke {@code super.setUp} and {@code super.tearDown} within
81   * them. These methods are used to clear and check for thread
82 < * assertion failures.</li>
82 > * assertion failures.
83   *
84   * <li>All delays and timeouts must use one of the constants {@code
85   * SHORT_DELAY_MS}, {@code SMALL_DELAY_MS}, {@code MEDIUM_DELAY_MS},
# Line 51 | Line 90 | import java.security.SecurityPermission;
90   * is always discriminable as larger than SHORT and smaller than
91   * MEDIUM.  And so on. These constants are set to conservative values,
92   * but even so, if there is ever any doubt, they can all be increased
93 < * in one spot to rerun tests on slower platforms.</li>
93 > * in one spot to rerun tests on slower platforms.
94   *
95 < * <li> All threads generated must be joined inside each test case
95 > * <li>All threads generated must be joined inside each test case
96   * method (or {@code fail} to do so) before returning from the
97   * method. The {@code joinPool} method can be used to do this when
98 < * using Executors.</li>
98 > * using Executors.
99   *
100   * </ol>
101   *
102 < * <p> <b>Other notes</b>
102 > * <p><b>Other notes</b>
103   * <ul>
104   *
105 < * <li> Usually, there is one testcase method per JSR166 method
105 > * <li>Usually, there is one testcase method per JSR166 method
106   * covering "normal" operation, and then as many exception-testing
107   * methods as there are exceptions the method can throw. Sometimes
108   * there are multiple tests per JSR166 method when the different
109   * "normal" behaviors differ significantly. And sometimes testcases
110   * cover multiple methods when they cannot be tested in
111 < * isolation.</li>
111 > * isolation.
112   *
113 < * <li> The documentation style for testcases is to provide as javadoc
113 > * <li>The documentation style for testcases is to provide as javadoc
114   * a simple sentence or two describing the property that the testcase
115   * method purports to test. The javadocs do not say anything about how
116 < * the property is tested. To find out, read the code.</li>
116 > * the property is tested. To find out, read the code.
117   *
118 < * <li> These tests are "conformance tests", and do not attempt to
118 > * <li>These tests are "conformance tests", and do not attempt to
119   * test throughput, latency, scalability or other performance factors
120   * (see the separate "jtreg" tests for a set intended to check these
121   * for the most central aspects of functionality.) So, most tests use
122   * the smallest sensible numbers of threads, collection sizes, etc
123 < * needed to check basic conformance.</li>
123 > * needed to check basic conformance.
124   *
125   * <li>The test classes currently do not declare inclusion in
126   * any particular package to simplify things for people integrating
127 < * them in TCK test suites.</li>
127 > * them in TCK test suites.
128   *
129 < * <li> As a convenience, the {@code main} of this class (JSR166TestCase)
130 < * runs all JSR166 unit tests.</li>
129 > * <li>As a convenience, the {@code main} of this class (JSR166TestCase)
130 > * runs all JSR166 unit tests.
131   *
132   * </ul>
133   */
# Line 96 | Line 135 | public class JSR166TestCase extends Test
135      private static final boolean useSecurityManager =
136          Boolean.getBoolean("jsr166.useSecurityManager");
137  
138 +    protected static final boolean expensiveTests =
139 +        Boolean.getBoolean("jsr166.expensiveTests");
140 +
141 +    /**
142 +     * If true, also run tests that are not part of the official tck
143 +     * because they test unspecified implementation details.
144 +     */
145 +    protected static final boolean testImplementationDetails =
146 +        Boolean.getBoolean("jsr166.testImplementationDetails");
147 +
148 +    /**
149 +     * If true, report on stdout all "slow" tests, that is, ones that
150 +     * take more than profileThreshold milliseconds to execute.
151 +     */
152 +    private static final boolean profileTests =
153 +        Boolean.getBoolean("jsr166.profileTests");
154 +
155 +    /**
156 +     * The number of milliseconds that tests are permitted for
157 +     * execution without being reported, when profileTests is set.
158 +     */
159 +    private static final long profileThreshold =
160 +        Long.getLong("jsr166.profileThreshold", 100);
161 +
162 +    /**
163 +     * The number of repetitions per test (for tickling rare bugs).
164 +     */
165 +    private static final int runsPerTest =
166 +        Integer.getInteger("jsr166.runsPerTest", 1);
167 +
168 +    /**
169 +     * The number of repetitions of the test suite (for finding leaks?).
170 +     */
171 +    private static final int suiteRuns =
172 +        Integer.getInteger("jsr166.suiteRuns", 1);
173 +
174 +    public JSR166TestCase() { super(); }
175 +    public JSR166TestCase(String name) { super(name); }
176 +
177 +    /**
178 +     * A filter for tests to run, matching strings of the form
179 +     * methodName(className), e.g. "testInvokeAll5(ForkJoinPoolTest)"
180 +     * Usefully combined with jsr166.runsPerTest.
181 +     */
182 +    private static final Pattern methodFilter = methodFilter();
183 +
184 +    private static Pattern methodFilter() {
185 +        String regex = System.getProperty("jsr166.methodFilter");
186 +        return (regex == null) ? null : Pattern.compile(regex);
187 +    }
188 +
189 +    public void runBare() throws Throwable {
190 +        if (methodFilter == null
191 +            || methodFilter.matcher(toString()).find())
192 +            super.runBare();
193 +    }
194 +
195 +    protected void runTest() throws Throwable {
196 +        for (int i = 0; i < runsPerTest; i++) {
197 +            if (profileTests)
198 +                runTestProfiled();
199 +            else
200 +                super.runTest();
201 +        }
202 +    }
203 +
204 +    protected void runTestProfiled() throws Throwable {
205 +        for (int i = 0; i < 2; i++) {
206 +            long startTime = System.nanoTime();
207 +            super.runTest();
208 +            long elapsedMillis = millisElapsedSince(startTime);
209 +            if (elapsedMillis < profileThreshold)
210 +                break;
211 +            // Never report first run of any test; treat it as a
212 +            // warmup run, notably to trigger all needed classloading,
213 +            if (i > 0)
214 +                System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
215 +        }
216 +    }
217 +
218      /**
219 <     * Runs all JSR166 unit tests using junit.textui.TestRunner
219 >     * Runs all JSR166 unit tests using junit.textui.TestRunner.
220       */
221      public static void main(String[] args) {
222 +        main(suite(), args);
223 +    }
224 +
225 +    /**
226 +     * Runs all unit tests in the given test suite.
227 +     * Actual behavior influenced by jsr166.* system properties.
228 +     */
229 +    static void main(Test suite, String[] args) {
230          if (useSecurityManager) {
231              System.err.println("Setting a permissive security manager");
232              Policy.setPolicy(permissivePolicy());
233              System.setSecurityManager(new SecurityManager());
234          }
235 <        int iters = 1;
236 <        if (args.length > 0)
237 <            iters = Integer.parseInt(args[0]);
238 <        Test s = suite();
112 <        for (int i = 0; i < iters; ++i) {
113 <            junit.textui.TestRunner.run(s);
235 >        for (int i = 0; i < suiteRuns; i++) {
236 >            TestResult result = junit.textui.TestRunner.run(suite);
237 >            if (!result.wasSuccessful())
238 >                System.exit(1);
239              System.gc();
240              System.runFinalization();
241          }
242 <        System.exit(0);
242 >    }
243 >
244 >    public static TestSuite newTestSuite(Object... suiteOrClasses) {
245 >        TestSuite suite = new TestSuite();
246 >        for (Object suiteOrClass : suiteOrClasses) {
247 >            if (suiteOrClass instanceof TestSuite)
248 >                suite.addTest((TestSuite) suiteOrClass);
249 >            else if (suiteOrClass instanceof Class)
250 >                suite.addTest(new TestSuite((Class<?>) suiteOrClass));
251 >            else
252 >                throw new ClassCastException("not a test suite or class");
253 >        }
254 >        return suite;
255 >    }
256 >
257 >    public static void addNamedTestClasses(TestSuite suite,
258 >                                           String... testClassNames) {
259 >        for (String testClassName : testClassNames) {
260 >            try {
261 >                Class<?> testClass = Class.forName(testClassName);
262 >                Method m = testClass.getDeclaredMethod("suite",
263 >                                                       new Class<?>[0]);
264 >                suite.addTest(newTestSuite((Test)m.invoke(null)));
265 >            } catch (Exception e) {
266 >                throw new Error("Missing test class", e);
267 >            }
268 >        }
269 >    }
270 >
271 >    public static final double JAVA_CLASS_VERSION;
272 >    public static final String JAVA_SPECIFICATION_VERSION;
273 >    static {
274 >        try {
275 >            JAVA_CLASS_VERSION = java.security.AccessController.doPrivileged(
276 >                new java.security.PrivilegedAction<Double>() {
277 >                public Double run() {
278 >                    return Double.valueOf(System.getProperty("java.class.version"));}});
279 >            JAVA_SPECIFICATION_VERSION = java.security.AccessController.doPrivileged(
280 >                new java.security.PrivilegedAction<String>() {
281 >                public String run() {
282 >                    return System.getProperty("java.specification.version");}});
283 >        } catch (Throwable t) {
284 >            throw new Error(t);
285 >        }
286 >    }
287 >
288 >    public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
289 >    public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
290 >    public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
291 >    public static boolean atLeastJava9() {
292 >        return JAVA_CLASS_VERSION >= 53.0
293 >            // As of 2015-09, java9 still uses 52.0 class file version
294 >            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?(9|[0-9][0-9])$");
295 >    }
296 >    public static boolean atLeastJava10() {
297 >        return JAVA_CLASS_VERSION >= 54.0
298 >            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?[0-9][0-9]$");
299      }
300  
301      /**
302 <     * Collects all JSR166 unit tests as one suite
302 >     * Collects all JSR166 unit tests as one suite.
303       */
304      public static Test suite() {
305 <        TestSuite suite = new TestSuite("JSR166 Unit Tests");
306 <
307 <        suite.addTest(new TestSuite(ForkJoinPoolTest.class));
308 <        suite.addTest(new TestSuite(ForkJoinTaskTest.class));
309 <        suite.addTest(new TestSuite(RecursiveActionTest.class));
310 <        suite.addTest(new TestSuite(RecursiveTaskTest.class));
311 <        suite.addTest(new TestSuite(LinkedTransferQueueTest.class));
312 <        suite.addTest(new TestSuite(PhaserTest.class));
313 <        suite.addTest(new TestSuite(ThreadLocalRandomTest.class));
314 <        suite.addTest(new TestSuite(AbstractExecutorServiceTest.class));
315 <        suite.addTest(new TestSuite(AbstractQueueTest.class));
316 <        suite.addTest(new TestSuite(AbstractQueuedSynchronizerTest.class));
317 <        suite.addTest(new TestSuite(AbstractQueuedLongSynchronizerTest.class));
318 <        suite.addTest(new TestSuite(ArrayBlockingQueueTest.class));
319 <        suite.addTest(new TestSuite(ArrayDequeTest.class));
320 <        suite.addTest(new TestSuite(AtomicBooleanTest.class));
321 <        suite.addTest(new TestSuite(AtomicIntegerArrayTest.class));
322 <        suite.addTest(new TestSuite(AtomicIntegerFieldUpdaterTest.class));
323 <        suite.addTest(new TestSuite(AtomicIntegerTest.class));
324 <        suite.addTest(new TestSuite(AtomicLongArrayTest.class));
325 <        suite.addTest(new TestSuite(AtomicLongFieldUpdaterTest.class));
326 <        suite.addTest(new TestSuite(AtomicLongTest.class));
327 <        suite.addTest(new TestSuite(AtomicMarkableReferenceTest.class));
328 <        suite.addTest(new TestSuite(AtomicReferenceArrayTest.class));
329 <        suite.addTest(new TestSuite(AtomicReferenceFieldUpdaterTest.class));
330 <        suite.addTest(new TestSuite(AtomicReferenceTest.class));
331 <        suite.addTest(new TestSuite(AtomicStampedReferenceTest.class));
332 <        suite.addTest(new TestSuite(ConcurrentHashMapTest.class));
333 <        suite.addTest(new TestSuite(ConcurrentLinkedDequeTest.class));
334 <        suite.addTest(new TestSuite(ConcurrentLinkedQueueTest.class));
335 <        suite.addTest(new TestSuite(ConcurrentSkipListMapTest.class));
336 <        suite.addTest(new TestSuite(ConcurrentSkipListSubMapTest.class));
337 <        suite.addTest(new TestSuite(ConcurrentSkipListSetTest.class));
338 <        suite.addTest(new TestSuite(ConcurrentSkipListSubSetTest.class));
339 <        suite.addTest(new TestSuite(CopyOnWriteArrayListTest.class));
340 <        suite.addTest(new TestSuite(CopyOnWriteArraySetTest.class));
341 <        suite.addTest(new TestSuite(CountDownLatchTest.class));
342 <        suite.addTest(new TestSuite(CyclicBarrierTest.class));
343 <        suite.addTest(new TestSuite(DelayQueueTest.class));
344 <        suite.addTest(new TestSuite(EntryTest.class));
345 <        suite.addTest(new TestSuite(ExchangerTest.class));
346 <        suite.addTest(new TestSuite(ExecutorsTest.class));
347 <        suite.addTest(new TestSuite(ExecutorCompletionServiceTest.class));
348 <        suite.addTest(new TestSuite(FutureTaskTest.class));
349 <        suite.addTest(new TestSuite(LinkedBlockingDequeTest.class));
350 <        suite.addTest(new TestSuite(LinkedBlockingQueueTest.class));
351 <        suite.addTest(new TestSuite(LinkedListTest.class));
352 <        suite.addTest(new TestSuite(LockSupportTest.class));
353 <        suite.addTest(new TestSuite(PriorityBlockingQueueTest.class));
354 <        suite.addTest(new TestSuite(PriorityQueueTest.class));
355 <        suite.addTest(new TestSuite(ReentrantLockTest.class));
356 <        suite.addTest(new TestSuite(ReentrantReadWriteLockTest.class));
357 <        suite.addTest(new TestSuite(ScheduledExecutorTest.class));
358 <        suite.addTest(new TestSuite(ScheduledExecutorSubclassTest.class));
359 <        suite.addTest(new TestSuite(SemaphoreTest.class));
360 <        suite.addTest(new TestSuite(SynchronousQueueTest.class));
361 <        suite.addTest(new TestSuite(SystemTest.class));
362 <        suite.addTest(new TestSuite(ThreadLocalTest.class));
363 <        suite.addTest(new TestSuite(ThreadPoolExecutorTest.class));
364 <        suite.addTest(new TestSuite(ThreadPoolExecutorSubclassTest.class));
365 <        suite.addTest(new TestSuite(ThreadTest.class));
366 <        suite.addTest(new TestSuite(TimeUnitTest.class));
367 <        suite.addTest(new TestSuite(TreeMapTest.class));
368 <        suite.addTest(new TestSuite(TreeSetTest.class));
369 <        suite.addTest(new TestSuite(TreeSubMapTest.class));
370 <        suite.addTest(new TestSuite(TreeSubSetTest.class));
305 >        // Java7+ test classes
306 >        TestSuite suite = newTestSuite(
307 >            ForkJoinPoolTest.suite(),
308 >            ForkJoinTaskTest.suite(),
309 >            RecursiveActionTest.suite(),
310 >            RecursiveTaskTest.suite(),
311 >            LinkedTransferQueueTest.suite(),
312 >            PhaserTest.suite(),
313 >            ThreadLocalRandomTest.suite(),
314 >            AbstractExecutorServiceTest.suite(),
315 >            AbstractQueueTest.suite(),
316 >            AbstractQueuedSynchronizerTest.suite(),
317 >            AbstractQueuedLongSynchronizerTest.suite(),
318 >            ArrayBlockingQueueTest.suite(),
319 >            ArrayDequeTest.suite(),
320 >            AtomicBooleanTest.suite(),
321 >            AtomicIntegerArrayTest.suite(),
322 >            AtomicIntegerFieldUpdaterTest.suite(),
323 >            AtomicIntegerTest.suite(),
324 >            AtomicLongArrayTest.suite(),
325 >            AtomicLongFieldUpdaterTest.suite(),
326 >            AtomicLongTest.suite(),
327 >            AtomicMarkableReferenceTest.suite(),
328 >            AtomicReferenceArrayTest.suite(),
329 >            AtomicReferenceFieldUpdaterTest.suite(),
330 >            AtomicReferenceTest.suite(),
331 >            AtomicStampedReferenceTest.suite(),
332 >            ConcurrentHashMapTest.suite(),
333 >            ConcurrentLinkedDequeTest.suite(),
334 >            ConcurrentLinkedQueueTest.suite(),
335 >            ConcurrentSkipListMapTest.suite(),
336 >            ConcurrentSkipListSubMapTest.suite(),
337 >            ConcurrentSkipListSetTest.suite(),
338 >            ConcurrentSkipListSubSetTest.suite(),
339 >            CopyOnWriteArrayListTest.suite(),
340 >            CopyOnWriteArraySetTest.suite(),
341 >            CountDownLatchTest.suite(),
342 >            CyclicBarrierTest.suite(),
343 >            DelayQueueTest.suite(),
344 >            EntryTest.suite(),
345 >            ExchangerTest.suite(),
346 >            ExecutorsTest.suite(),
347 >            ExecutorCompletionServiceTest.suite(),
348 >            FutureTaskTest.suite(),
349 >            LinkedBlockingDequeTest.suite(),
350 >            LinkedBlockingQueueTest.suite(),
351 >            LinkedListTest.suite(),
352 >            LockSupportTest.suite(),
353 >            PriorityBlockingQueueTest.suite(),
354 >            PriorityQueueTest.suite(),
355 >            ReentrantLockTest.suite(),
356 >            ReentrantReadWriteLockTest.suite(),
357 >            ScheduledExecutorTest.suite(),
358 >            ScheduledExecutorSubclassTest.suite(),
359 >            SemaphoreTest.suite(),
360 >            SynchronousQueueTest.suite(),
361 >            SystemTest.suite(),
362 >            ThreadLocalTest.suite(),
363 >            ThreadPoolExecutorTest.suite(),
364 >            ThreadPoolExecutorSubclassTest.suite(),
365 >            ThreadTest.suite(),
366 >            TimeUnitTest.suite(),
367 >            TreeMapTest.suite(),
368 >            TreeSetTest.suite(),
369 >            TreeSubMapTest.suite(),
370 >            TreeSubSetTest.suite());
371 >
372 >        // Java8+ test classes
373 >        if (atLeastJava8()) {
374 >            String[] java8TestClassNames = {
375 >                "Atomic8Test",
376 >                "CompletableFutureTest",
377 >                "ConcurrentHashMap8Test",
378 >                "CountedCompleterTest",
379 >                "DoubleAccumulatorTest",
380 >                "DoubleAdderTest",
381 >                "ForkJoinPool8Test",
382 >                "ForkJoinTask8Test",
383 >                "LongAccumulatorTest",
384 >                "LongAdderTest",
385 >                "SplittableRandomTest",
386 >                "StampedLockTest",
387 >                "SubmissionPublisherTest",
388 >                "ThreadLocalRandom8Test",
389 >            };
390 >            addNamedTestClasses(suite, java8TestClassNames);
391 >        }
392 >
393 >        // Java9+ test classes
394 >        if (atLeastJava9()) {
395 >            String[] java9TestClassNames = {
396 >                // Currently empty, but expecting varhandle tests
397 >            };
398 >            addNamedTestClasses(suite, java9TestClassNames);
399 >        }
400  
401          return suite;
402      }
403  
404 +    /** Returns list of junit-style test method names in given class. */
405 +    public static ArrayList<String> testMethodNames(Class<?> testClass) {
406 +        Method[] methods = testClass.getDeclaredMethods();
407 +        ArrayList<String> names = new ArrayList<String>(methods.length);
408 +        for (Method method : methods) {
409 +            if (method.getName().startsWith("test")
410 +                && Modifier.isPublic(method.getModifiers())
411 +                // method.getParameterCount() requires jdk8+
412 +                && method.getParameterTypes().length == 0) {
413 +                names.add(method.getName());
414 +            }
415 +        }
416 +        return names;
417 +    }
418 +
419 +    /**
420 +     * Returns junit-style testSuite for the given test class, but
421 +     * parameterized by passing extra data to each test.
422 +     */
423 +    public static <ExtraData> Test parameterizedTestSuite
424 +        (Class<? extends JSR166TestCase> testClass,
425 +         Class<ExtraData> dataClass,
426 +         ExtraData data) {
427 +        try {
428 +            TestSuite suite = new TestSuite();
429 +            Constructor c =
430 +                testClass.getDeclaredConstructor(dataClass, String.class);
431 +            for (String methodName : testMethodNames(testClass))
432 +                suite.addTest((Test) c.newInstance(data, methodName));
433 +            return suite;
434 +        } catch (Exception e) {
435 +            throw new Error(e);
436 +        }
437 +    }
438 +
439 +    /**
440 +     * Returns junit-style testSuite for the jdk8 extension of the
441 +     * given test class, but parameterized by passing extra data to
442 +     * each test.  Uses reflection to allow compilation in jdk7.
443 +     */
444 +    public static <ExtraData> Test jdk8ParameterizedTestSuite
445 +        (Class<? extends JSR166TestCase> testClass,
446 +         Class<ExtraData> dataClass,
447 +         ExtraData data) {
448 +        if (atLeastJava8()) {
449 +            String name = testClass.getName();
450 +            String name8 = name.replaceAll("Test$", "8Test");
451 +            if (name.equals(name8)) throw new Error(name);
452 +            try {
453 +                return (Test)
454 +                    Class.forName(name8)
455 +                    .getMethod("testSuite", new Class[] { dataClass })
456 +                    .invoke(null, data);
457 +            } catch (Exception e) {
458 +                throw new Error(e);
459 +            }
460 +        } else {
461 +            return new TestSuite();
462 +        }
463 +
464 +    }
465 +
466 +    // Delays for timing-dependent tests, in milliseconds.
467  
468      public static long SHORT_DELAY_MS;
469      public static long SMALL_DELAY_MS;
470      public static long MEDIUM_DELAY_MS;
471      public static long LONG_DELAY_MS;
472  
200
473      /**
474       * Returns the shortest timed delay. This could
475       * be reimplemented to use for example a Property.
# Line 206 | Line 478 | public class JSR166TestCase extends Test
478          return 50;
479      }
480  
209
481      /**
482       * Sets delays as multiples of SHORT_DELAY.
483       */
# Line 214 | Line 485 | public class JSR166TestCase extends Test
485          SHORT_DELAY_MS = getShortDelay();
486          SMALL_DELAY_MS  = SHORT_DELAY_MS * 5;
487          MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
488 <        LONG_DELAY_MS   = SHORT_DELAY_MS * 50;
488 >        LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
489 >    }
490 >
491 >    /**
492 >     * Returns a timeout in milliseconds to be used in tests that
493 >     * verify that operations block or time out.
494 >     */
495 >    long timeoutMillis() {
496 >        return SHORT_DELAY_MS / 4;
497 >    }
498 >
499 >    /**
500 >     * Returns a new Date instance representing a time at least
501 >     * delayMillis milliseconds in the future.
502 >     */
503 >    Date delayedDate(long delayMillis) {
504 >        // Add 1 because currentTimeMillis is known to round into the past.
505 >        return new Date(System.currentTimeMillis() + delayMillis + 1);
506      }
507  
508      /**
# Line 237 | Line 525 | public class JSR166TestCase extends Test
525          setDelays();
526      }
527  
528 +    void tearDownFail(String format, Object... args) {
529 +        String msg = toString() + ": " + String.format(format, args);
530 +        System.err.println(msg);
531 +        printAllStackTraces();
532 +        throw new AssertionFailedError(msg);
533 +    }
534 +
535      /**
536 +     * Extra checks that get done for all test cases.
537 +     *
538       * Triggers test case failure if any thread assertions have failed,
539       * by rethrowing, in the test harness thread, any exception recorded
540       * earlier by threadRecordFailure.
541 +     *
542 +     * Triggers test case failure if interrupt status is set in the main thread.
543       */
544      public void tearDown() throws Exception {
545 <        Throwable t = threadFailure.get();
545 >        Throwable t = threadFailure.getAndSet(null);
546          if (t != null) {
547              if (t instanceof Error)
548                  throw (Error) t;
# Line 251 | Line 550 | public class JSR166TestCase extends Test
550                  throw (RuntimeException) t;
551              else if (t instanceof Exception)
552                  throw (Exception) t;
553 <            else
554 <                throw new AssertionError(t);
553 >            else {
554 >                AssertionFailedError afe =
555 >                    new AssertionFailedError(t.toString());
556 >                afe.initCause(t);
557 >                throw afe;
558 >            }
559          }
560 +
561 +        if (Thread.interrupted())
562 +            tearDownFail("interrupt status set in main thread");
563 +
564 +        checkForkJoinPoolThreadLeaks();
565 +    }
566 +
567 +    /**
568 +     * Finds missing try { ... } finally { joinPool(e); }
569 +     */
570 +    void checkForkJoinPoolThreadLeaks() throws InterruptedException {
571 +        Thread[] survivors = new Thread[7];
572 +        int count = Thread.enumerate(survivors);
573 +        for (int i = 0; i < count; i++) {
574 +            Thread thread = survivors[i];
575 +            String name = thread.getName();
576 +            if (name.startsWith("ForkJoinPool-")) {
577 +                // give thread some time to terminate
578 +                thread.join(LONG_DELAY_MS);
579 +                if (thread.isAlive())
580 +                    tearDownFail("Found leaked ForkJoinPool thread thread=%s",
581 +                                 thread);
582 +            }
583 +        }
584 +
585 +        if (!ForkJoinPool.commonPool()
586 +            .awaitQuiescence(LONG_DELAY_MS, MILLISECONDS))
587 +            tearDownFail("ForkJoin common pool thread stuck");
588      }
589  
590      /**
591       * Just like fail(reason), but additionally recording (using
592 <     * threadRecordFailure) any AssertionError thrown, so that the current
593 <     * testcase will fail.
592 >     * threadRecordFailure) any AssertionFailedError thrown, so that
593 >     * the current testcase will fail.
594       */
595      public void threadFail(String reason) {
596          try {
597              fail(reason);
598 <        } catch (Throwable t) {
598 >        } catch (AssertionFailedError t) {
599              threadRecordFailure(t);
600              fail(reason);
601          }
# Line 272 | Line 603 | public class JSR166TestCase extends Test
603  
604      /**
605       * Just like assertTrue(b), but additionally recording (using
606 <     * threadRecordFailure) any AssertionError thrown, so that the current
607 <     * testcase will fail.
606 >     * threadRecordFailure) any AssertionFailedError thrown, so that
607 >     * the current testcase will fail.
608       */
609      public void threadAssertTrue(boolean b) {
610          try {
611              assertTrue(b);
612 <        } catch (AssertionError t) {
612 >        } catch (AssertionFailedError t) {
613              threadRecordFailure(t);
614              throw t;
615          }
# Line 286 | Line 617 | public class JSR166TestCase extends Test
617  
618      /**
619       * Just like assertFalse(b), but additionally recording (using
620 <     * threadRecordFailure) any AssertionError thrown, so that the
621 <     * current testcase will fail.
620 >     * threadRecordFailure) any AssertionFailedError thrown, so that
621 >     * the current testcase will fail.
622       */
623      public void threadAssertFalse(boolean b) {
624          try {
625              assertFalse(b);
626 <        } catch (AssertionError t) {
626 >        } catch (AssertionFailedError t) {
627              threadRecordFailure(t);
628              throw t;
629          }
# Line 300 | Line 631 | public class JSR166TestCase extends Test
631  
632      /**
633       * Just like assertNull(x), but additionally recording (using
634 <     * threadRecordFailure) any AssertionError thrown, so that the
635 <     * current testcase will fail.
634 >     * threadRecordFailure) any AssertionFailedError thrown, so that
635 >     * the current testcase will fail.
636       */
637      public void threadAssertNull(Object x) {
638          try {
639              assertNull(x);
640 <        } catch (AssertionError t) {
640 >        } catch (AssertionFailedError t) {
641              threadRecordFailure(t);
642              throw t;
643          }
# Line 314 | Line 645 | public class JSR166TestCase extends Test
645  
646      /**
647       * Just like assertEquals(x, y), but additionally recording (using
648 <     * threadRecordFailure) any AssertionError thrown, so that the
649 <     * current testcase will fail.
648 >     * threadRecordFailure) any AssertionFailedError thrown, so that
649 >     * the current testcase will fail.
650       */
651      public void threadAssertEquals(long x, long y) {
652          try {
653              assertEquals(x, y);
654 <        } catch (AssertionError t) {
654 >        } catch (AssertionFailedError t) {
655              threadRecordFailure(t);
656              throw t;
657          }
# Line 328 | Line 659 | public class JSR166TestCase extends Test
659  
660      /**
661       * Just like assertEquals(x, y), but additionally recording (using
662 <     * threadRecordFailure) any AssertionError thrown, so that the
663 <     * current testcase will fail.
662 >     * threadRecordFailure) any AssertionFailedError thrown, so that
663 >     * the current testcase will fail.
664       */
665      public void threadAssertEquals(Object x, Object y) {
666          try {
667              assertEquals(x, y);
668 <        } catch (AssertionError t) {
669 <            threadRecordFailure(t);
670 <            throw t;
668 >        } catch (AssertionFailedError fail) {
669 >            threadRecordFailure(fail);
670 >            throw fail;
671 >        } catch (Throwable fail) {
672 >            threadUnexpectedException(fail);
673          }
674      }
675  
676      /**
677       * Just like assertSame(x, y), but additionally recording (using
678 <     * threadRecordFailure) any AssertionError thrown, so that the
679 <     * current testcase will fail.
678 >     * threadRecordFailure) any AssertionFailedError thrown, so that
679 >     * the current testcase will fail.
680       */
681      public void threadAssertSame(Object x, Object y) {
682          try {
683              assertSame(x, y);
684 <        } catch (AssertionError t) {
685 <            threadRecordFailure(t);
686 <            throw t;
684 >        } catch (AssertionFailedError fail) {
685 >            threadRecordFailure(fail);
686 >            throw fail;
687          }
688      }
689  
# Line 369 | Line 702 | public class JSR166TestCase extends Test
702      }
703  
704      /**
705 <     * Calls threadFail with message "Unexpected exception" + ex.
705 >     * Records the given exception using {@link #threadRecordFailure},
706 >     * then rethrows the exception, wrapping it in an
707 >     * AssertionFailedError if necessary.
708       */
709      public void threadUnexpectedException(Throwable t) {
710          threadRecordFailure(t);
711          t.printStackTrace();
377        // Rethrow, wrapping in an AssertionError if necessary
712          if (t instanceof RuntimeException)
713              throw (RuntimeException) t;
714          else if (t instanceof Error)
715              throw (Error) t;
716          else {
717 <            AssertionError ae = new AssertionError("unexpected exception: " + t);
718 <            t.initCause(t);
719 <            throw ae;
720 <        }            
717 >            AssertionFailedError afe =
718 >                new AssertionFailedError("unexpected exception: " + t);
719 >            afe.initCause(t);
720 >            throw afe;
721 >        }
722 >    }
723 >
724 >    /**
725 >     * Delays, via Thread.sleep, for the given millisecond delay, but
726 >     * if the sleep is shorter than specified, may re-sleep or yield
727 >     * until time elapses.
728 >     */
729 >    static void delay(long millis) throws InterruptedException {
730 >        long startTime = System.nanoTime();
731 >        long ns = millis * 1000 * 1000;
732 >        for (;;) {
733 >            if (millis > 0L)
734 >                Thread.sleep(millis);
735 >            else // too short to sleep
736 >                Thread.yield();
737 >            long d = ns - (System.nanoTime() - startTime);
738 >            if (d > 0L)
739 >                millis = d / (1000 * 1000);
740 >            else
741 >                break;
742 >        }
743      }
744  
745      /**
746       * Waits out termination of a thread pool or fails doing so.
747       */
748 <    public void joinPool(ExecutorService exec) {
748 >    void joinPool(ExecutorService pool) {
749          try {
750 <            exec.shutdown();
751 <            assertTrue("ExecutorService did not terminate in a timely manner",
752 <                       exec.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
750 >            pool.shutdown();
751 >            if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS))
752 >                fail("ExecutorService " + pool +
753 >                     " did not terminate in a timely manner");
754          } catch (SecurityException ok) {
755              // Allowed in case test doesn't have privs
756 <        } catch (InterruptedException ie) {
756 >        } catch (InterruptedException fail) {
757 >            fail("Unexpected InterruptedException");
758 >        }
759 >    }
760 >
761 >    /** Like Runnable, but with the freedom to throw anything */
762 >    interface Action { public void run() throws Throwable; }
763 >
764 >    /**
765 >     * Runs all the given actions in parallel, failing if any fail.
766 >     * Useful for running multiple variants of tests that are
767 >     * necessarily individually slow because they must block.
768 >     */
769 >    void testInParallel(Action ... actions) {
770 >        ExecutorService pool = Executors.newCachedThreadPool();
771 >        try {
772 >            ArrayList<Future<?>> futures = new ArrayList<>(actions.length);
773 >            for (final Action action : actions)
774 >                futures.add(pool.submit(new CheckedRunnable() {
775 >                    public void realRun() throws Throwable { action.run();}}));
776 >            for (Future<?> future : futures)
777 >                try {
778 >                    assertNull(future.get(LONG_DELAY_MS, MILLISECONDS));
779 >                } catch (ExecutionException ex) {
780 >                    threadUnexpectedException(ex.getCause());
781 >                } catch (Exception ex) {
782 >                    threadUnexpectedException(ex);
783 >                }
784 >        } finally {
785 >            joinPool(pool);
786 >        }
787 >    }
788 >
789 >    /**
790 >     * A debugging tool to print all stack traces, as jstack does.
791 >     */
792 >    static void printAllStackTraces() {
793 >        for (ThreadInfo info :
794 >                 ManagementFactory.getThreadMXBean()
795 >                 .dumpAllThreads(true, true))
796 >            System.err.print(info);
797 >    }
798 >
799 >    /**
800 >     * Checks that thread does not terminate within the default
801 >     * millisecond delay of {@code timeoutMillis()}.
802 >     */
803 >    void assertThreadStaysAlive(Thread thread) {
804 >        assertThreadStaysAlive(thread, timeoutMillis());
805 >    }
806 >
807 >    /**
808 >     * Checks that thread does not terminate within the given millisecond delay.
809 >     */
810 >    void assertThreadStaysAlive(Thread thread, long millis) {
811 >        try {
812 >            // No need to optimize the failing case via Thread.join.
813 >            delay(millis);
814 >            assertTrue(thread.isAlive());
815 >        } catch (InterruptedException fail) {
816              fail("Unexpected InterruptedException");
817          }
818      }
819  
820 +    /**
821 +     * Checks that the threads do not terminate within the default
822 +     * millisecond delay of {@code timeoutMillis()}.
823 +     */
824 +    void assertThreadsStayAlive(Thread... threads) {
825 +        assertThreadsStayAlive(timeoutMillis(), threads);
826 +    }
827 +
828 +    /**
829 +     * Checks that the threads do not terminate within the given millisecond delay.
830 +     */
831 +    void assertThreadsStayAlive(long millis, Thread... threads) {
832 +        try {
833 +            // No need to optimize the failing case via Thread.join.
834 +            delay(millis);
835 +            for (Thread thread : threads)
836 +                assertTrue(thread.isAlive());
837 +        } catch (InterruptedException fail) {
838 +            fail("Unexpected InterruptedException");
839 +        }
840 +    }
841 +
842 +    /**
843 +     * Checks that future.get times out, with the default timeout of
844 +     * {@code timeoutMillis()}.
845 +     */
846 +    void assertFutureTimesOut(Future future) {
847 +        assertFutureTimesOut(future, timeoutMillis());
848 +    }
849 +
850 +    /**
851 +     * Checks that future.get times out, with the given millisecond timeout.
852 +     */
853 +    void assertFutureTimesOut(Future future, long timeoutMillis) {
854 +        long startTime = System.nanoTime();
855 +        try {
856 +            future.get(timeoutMillis, MILLISECONDS);
857 +            shouldThrow();
858 +        } catch (TimeoutException success) {
859 +        } catch (Exception fail) {
860 +            threadUnexpectedException(fail);
861 +        } finally { future.cancel(true); }
862 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
863 +    }
864  
865      /**
866       * Fails with message "should throw exception".
# Line 417 | Line 877 | public class JSR166TestCase extends Test
877      }
878  
879      /**
420     * Fails with message "Unexpected exception: " + ex.
421     */
422    public void unexpectedException(Throwable ex) {
423        ex.printStackTrace();
424        fail("Unexpected exception: " + ex);
425    }
426
427
428    /**
880       * The number of elements to place in collections, arrays, etc.
881       */
882      public static final int SIZE = 20;
# Line 450 | Line 901 | public class JSR166TestCase extends Test
901      public static final Integer m6  = new Integer(-6);
902      public static final Integer m10 = new Integer(-10);
903  
453
904      /**
905       * Runs Runnable r with a security policy that permits precisely
906       * the specified permissions.  If there is no current security
# Line 462 | Line 912 | public class JSR166TestCase extends Test
912          SecurityManager sm = System.getSecurityManager();
913          if (sm == null) {
914              r.run();
915 +        }
916 +        runWithSecurityManagerWithPermissions(r, permissions);
917 +    }
918 +
919 +    /**
920 +     * Runs Runnable r with a security policy that permits precisely
921 +     * the specified permissions.  If there is no current security
922 +     * manager, a temporary one is set for the duration of the
923 +     * Runnable.  We require that any security manager permit
924 +     * getPolicy/setPolicy.
925 +     */
926 +    public void runWithSecurityManagerWithPermissions(Runnable r,
927 +                                                      Permission... permissions) {
928 +        SecurityManager sm = System.getSecurityManager();
929 +        if (sm == null) {
930              Policy savedPolicy = Policy.getPolicy();
931              try {
932                  Policy.setPolicy(permissivePolicy());
933                  System.setSecurityManager(new SecurityManager());
934 <                runWithPermissions(r, permissions);
934 >                runWithSecurityManagerWithPermissions(r, permissions);
935              } finally {
936                  System.setSecurityManager(null);
937                  Policy.setPolicy(savedPolicy);
# Line 514 | Line 979 | public class JSR166TestCase extends Test
979              return perms.implies(p);
980          }
981          public void refresh() {}
982 +        public String toString() {
983 +            List<Permission> ps = new ArrayList<Permission>();
984 +            for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
985 +                ps.add(e.nextElement());
986 +            return "AdjustablePolicy with permissions " + ps;
987 +        }
988      }
989  
990      /**
# Line 536 | Line 1007 | public class JSR166TestCase extends Test
1007      }
1008  
1009      /**
1010 <     * Sleep until the timeout has elapsed, or interrupted.
1011 <     * Does <em>NOT</em> throw InterruptedException.
1010 >     * Sleeps until the given time has elapsed.
1011 >     * Throws AssertionFailedError if interrupted.
1012       */
1013 <    void sleepTillInterrupted(long timeoutMillis) {
1013 >    void sleep(long millis) {
1014          try {
1015 <            Thread.sleep(timeoutMillis);
1016 <        } catch (InterruptedException wakeup) {}
1015 >            delay(millis);
1016 >        } catch (InterruptedException fail) {
1017 >            AssertionFailedError afe =
1018 >                new AssertionFailedError("Unexpected InterruptedException");
1019 >            afe.initCause(fail);
1020 >            throw afe;
1021 >        }
1022      }
1023  
1024      /**
1025 <     * Returns a new started Thread running the given runnable.
1025 >     * Spin-waits up to the specified number of milliseconds for the given
1026 >     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1027 >     */
1028 >    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
1029 >        long startTime = System.nanoTime();
1030 >        for (;;) {
1031 >            Thread.State s = thread.getState();
1032 >            if (s == Thread.State.BLOCKED ||
1033 >                s == Thread.State.WAITING ||
1034 >                s == Thread.State.TIMED_WAITING)
1035 >                return;
1036 >            else if (s == Thread.State.TERMINATED)
1037 >                fail("Unexpected thread termination");
1038 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
1039 >                threadAssertTrue(thread.isAlive());
1040 >                return;
1041 >            }
1042 >            Thread.yield();
1043 >        }
1044 >    }
1045 >
1046 >    /**
1047 >     * Waits up to LONG_DELAY_MS for the given thread to enter a wait
1048 >     * state: BLOCKED, WAITING, or TIMED_WAITING.
1049 >     */
1050 >    void waitForThreadToEnterWaitState(Thread thread) {
1051 >        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
1052 >    }
1053 >
1054 >    /**
1055 >     * Returns the number of milliseconds since time given by
1056 >     * startNanoTime, which must have been previously returned from a
1057 >     * call to {@link System#nanoTime()}.
1058 >     */
1059 >    static long millisElapsedSince(long startNanoTime) {
1060 >        return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
1061 >    }
1062 >
1063 > //     void assertTerminatesPromptly(long timeoutMillis, Runnable r) {
1064 > //         long startTime = System.nanoTime();
1065 > //         try {
1066 > //             r.run();
1067 > //         } catch (Throwable fail) { threadUnexpectedException(fail); }
1068 > //         if (millisElapsedSince(startTime) > timeoutMillis/2)
1069 > //             throw new AssertionFailedError("did not return promptly");
1070 > //     }
1071 >
1072 > //     void assertTerminatesPromptly(Runnable r) {
1073 > //         assertTerminatesPromptly(LONG_DELAY_MS/2, r);
1074 > //     }
1075 >
1076 >    /**
1077 >     * Checks that timed f.get() returns the expected value, and does not
1078 >     * wait for the timeout to elapse before returning.
1079 >     */
1080 >    <T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) {
1081 >        long startTime = System.nanoTime();
1082 >        try {
1083 >            assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
1084 >        } catch (Throwable fail) { threadUnexpectedException(fail); }
1085 >        if (millisElapsedSince(startTime) > timeoutMillis/2)
1086 >            throw new AssertionFailedError("timed get did not return promptly");
1087 >    }
1088 >
1089 >    <T> void checkTimedGet(Future<T> f, T expectedValue) {
1090 >        checkTimedGet(f, expectedValue, LONG_DELAY_MS);
1091 >    }
1092 >
1093 >    /**
1094 >     * Returns a new started daemon Thread running the given runnable.
1095       */
1096      Thread newStartedThread(Runnable runnable) {
1097          Thread t = new Thread(runnable);
1098 +        t.setDaemon(true);
1099          t.start();
1100          return t;
1101      }
1102  
1103 +    /**
1104 +     * Waits for the specified time (in milliseconds) for the thread
1105 +     * to terminate (using {@link Thread#join(long)}), else interrupts
1106 +     * the thread (in the hope that it may terminate later) and fails.
1107 +     */
1108 +    void awaitTermination(Thread t, long timeoutMillis) {
1109 +        try {
1110 +            t.join(timeoutMillis);
1111 +        } catch (InterruptedException fail) {
1112 +            threadUnexpectedException(fail);
1113 +        } finally {
1114 +            if (t.getState() != Thread.State.TERMINATED) {
1115 +                t.interrupt();
1116 +                fail("Test timed out");
1117 +            }
1118 +        }
1119 +    }
1120 +
1121 +    /**
1122 +     * Waits for LONG_DELAY_MS milliseconds for the thread to
1123 +     * terminate (using {@link Thread#join(long)}), else interrupts
1124 +     * the thread (in the hope that it may terminate later) and fails.
1125 +     */
1126 +    void awaitTermination(Thread t) {
1127 +        awaitTermination(t, LONG_DELAY_MS);
1128 +    }
1129 +
1130      // Some convenient Runnable classes
1131  
1132      public abstract class CheckedRunnable implements Runnable {
# Line 562 | Line 1135 | public class JSR166TestCase extends Test
1135          public final void run() {
1136              try {
1137                  realRun();
1138 <            } catch (Throwable t) {
1139 <                threadUnexpectedException(t);
1138 >            } catch (Throwable fail) {
1139 >                threadUnexpectedException(fail);
1140              }
1141          }
1142      }
# Line 616 | Line 1189 | public class JSR166TestCase extends Test
1189                  realRun();
1190                  threadShouldThrow("InterruptedException");
1191              } catch (InterruptedException success) {
1192 <            } catch (Throwable t) {
1193 <                threadUnexpectedException(t);
1192 >                threadAssertFalse(Thread.interrupted());
1193 >            } catch (Throwable fail) {
1194 >                threadUnexpectedException(fail);
1195              }
1196          }
1197      }
# Line 628 | Line 1202 | public class JSR166TestCase extends Test
1202          public final T call() {
1203              try {
1204                  return realCall();
1205 <            } catch (Throwable t) {
1206 <                threadUnexpectedException(t);
1205 >            } catch (Throwable fail) {
1206 >                threadUnexpectedException(fail);
1207                  return null;
1208              }
1209          }
# Line 645 | Line 1219 | public class JSR166TestCase extends Test
1219                  threadShouldThrow("InterruptedException");
1220                  return result;
1221              } catch (InterruptedException success) {
1222 <            } catch (Throwable t) {
1223 <                threadUnexpectedException(t);
1222 >                threadAssertFalse(Thread.interrupted());
1223 >            } catch (Throwable fail) {
1224 >                threadUnexpectedException(fail);
1225              }
1226              return null;
1227          }
# Line 663 | Line 1238 | public class JSR166TestCase extends Test
1238      public static final String TEST_STRING = "a test string";
1239  
1240      public static class StringTask implements Callable<String> {
1241 <        public String call() { return TEST_STRING; }
1241 >        final String value;
1242 >        public StringTask() { this(TEST_STRING); }
1243 >        public StringTask(String value) { this.value = value; }
1244 >        public String call() { return value; }
1245      }
1246  
1247      public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
1248          return new CheckedCallable<String>() {
1249 <            public String realCall() {
1249 >            protected String realCall() {
1250                  try {
1251                      latch.await();
1252                  } catch (InterruptedException quittingTime) {}
# Line 676 | Line 1254 | public class JSR166TestCase extends Test
1254              }};
1255      }
1256  
1257 +    public Runnable awaiter(final CountDownLatch latch) {
1258 +        return new CheckedRunnable() {
1259 +            public void realRun() throws InterruptedException {
1260 +                await(latch);
1261 +            }};
1262 +    }
1263 +
1264 +    public void await(CountDownLatch latch) {
1265 +        try {
1266 +            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1267 +        } catch (Throwable fail) {
1268 +            threadUnexpectedException(fail);
1269 +        }
1270 +    }
1271 +
1272 +    public void await(Semaphore semaphore) {
1273 +        try {
1274 +            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1275 +        } catch (Throwable fail) {
1276 +            threadUnexpectedException(fail);
1277 +        }
1278 +    }
1279 +
1280 + //     /**
1281 + //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1282 + //      */
1283 + //     public void await(AtomicBoolean flag) {
1284 + //         await(flag, LONG_DELAY_MS);
1285 + //     }
1286 +
1287 + //     /**
1288 + //      * Spin-waits up to the specified timeout until flag becomes true.
1289 + //      */
1290 + //     public void await(AtomicBoolean flag, long timeoutMillis) {
1291 + //         long startTime = System.nanoTime();
1292 + //         while (!flag.get()) {
1293 + //             if (millisElapsedSince(startTime) > timeoutMillis)
1294 + //                 throw new AssertionFailedError("timed out");
1295 + //             Thread.yield();
1296 + //         }
1297 + //     }
1298 +
1299      public static class NPETask implements Callable<String> {
1300          public String call() { throw new NullPointerException(); }
1301      }
# Line 686 | Line 1306 | public class JSR166TestCase extends Test
1306  
1307      public class ShortRunnable extends CheckedRunnable {
1308          protected void realRun() throws Throwable {
1309 <            Thread.sleep(SHORT_DELAY_MS);
1309 >            delay(SHORT_DELAY_MS);
1310          }
1311      }
1312  
1313      public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1314          protected void realRun() throws InterruptedException {
1315 <            Thread.sleep(SHORT_DELAY_MS);
1315 >            delay(SHORT_DELAY_MS);
1316          }
1317      }
1318  
1319      public class SmallRunnable extends CheckedRunnable {
1320          protected void realRun() throws Throwable {
1321 <            Thread.sleep(SMALL_DELAY_MS);
1321 >            delay(SMALL_DELAY_MS);
1322          }
1323      }
1324  
1325      public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1326          protected void realRun() {
1327              try {
1328 <                Thread.sleep(SMALL_DELAY_MS);
1328 >                delay(SMALL_DELAY_MS);
1329              } catch (InterruptedException ok) {}
1330          }
1331      }
1332  
1333      public class SmallCallable extends CheckedCallable {
1334          protected Object realCall() throws InterruptedException {
1335 <            Thread.sleep(SMALL_DELAY_MS);
1335 >            delay(SMALL_DELAY_MS);
1336              return Boolean.TRUE;
1337          }
1338      }
1339  
720    public class SmallInterruptedRunnable extends CheckedInterruptedRunnable {
721        protected void realRun() throws InterruptedException {
722            Thread.sleep(SMALL_DELAY_MS);
723        }
724    }
725
1340      public class MediumRunnable extends CheckedRunnable {
1341          protected void realRun() throws Throwable {
1342 <            Thread.sleep(MEDIUM_DELAY_MS);
1342 >            delay(MEDIUM_DELAY_MS);
1343          }
1344      }
1345  
1346      public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1347          protected void realRun() throws InterruptedException {
1348 <            Thread.sleep(MEDIUM_DELAY_MS);
1348 >            delay(MEDIUM_DELAY_MS);
1349          }
1350      }
1351  
1352 +    public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1353 +        return new CheckedRunnable() {
1354 +            protected void realRun() {
1355 +                try {
1356 +                    delay(timeoutMillis);
1357 +                } catch (InterruptedException ok) {}
1358 +            }};
1359 +    }
1360 +
1361      public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1362          protected void realRun() {
1363              try {
1364 <                Thread.sleep(MEDIUM_DELAY_MS);
1364 >                delay(MEDIUM_DELAY_MS);
1365              } catch (InterruptedException ok) {}
1366          }
1367      }
# Line 746 | Line 1369 | public class JSR166TestCase extends Test
1369      public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1370          protected void realRun() {
1371              try {
1372 <                Thread.sleep(LONG_DELAY_MS);
1372 >                delay(LONG_DELAY_MS);
1373              } catch (InterruptedException ok) {}
1374          }
1375      }
# Line 760 | Line 1383 | public class JSR166TestCase extends Test
1383          }
1384      }
1385  
1386 +    public interface TrackedRunnable extends Runnable {
1387 +        boolean isDone();
1388 +    }
1389 +
1390 +    public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
1391 +        return new TrackedRunnable() {
1392 +                private volatile boolean done = false;
1393 +                public boolean isDone() { return done; }
1394 +                public void run() {
1395 +                    try {
1396 +                        delay(timeoutMillis);
1397 +                        done = true;
1398 +                    } catch (InterruptedException ok) {}
1399 +                }
1400 +            };
1401 +    }
1402 +
1403      public static class TrackedShortRunnable implements Runnable {
1404          public volatile boolean done = false;
1405          public void run() {
1406              try {
1407 <                Thread.sleep(SMALL_DELAY_MS);
1407 >                delay(SHORT_DELAY_MS);
1408 >                done = true;
1409 >            } catch (InterruptedException ok) {}
1410 >        }
1411 >    }
1412 >
1413 >    public static class TrackedSmallRunnable implements Runnable {
1414 >        public volatile boolean done = false;
1415 >        public void run() {
1416 >            try {
1417 >                delay(SMALL_DELAY_MS);
1418                  done = true;
1419              } catch (InterruptedException ok) {}
1420          }
# Line 774 | Line 1424 | public class JSR166TestCase extends Test
1424          public volatile boolean done = false;
1425          public void run() {
1426              try {
1427 <                Thread.sleep(MEDIUM_DELAY_MS);
1427 >                delay(MEDIUM_DELAY_MS);
1428                  done = true;
1429              } catch (InterruptedException ok) {}
1430          }
# Line 784 | Line 1434 | public class JSR166TestCase extends Test
1434          public volatile boolean done = false;
1435          public void run() {
1436              try {
1437 <                Thread.sleep(LONG_DELAY_MS);
1437 >                delay(LONG_DELAY_MS);
1438                  done = true;
1439              } catch (InterruptedException ok) {}
1440          }
# Line 801 | Line 1451 | public class JSR166TestCase extends Test
1451          public volatile boolean done = false;
1452          public Object call() {
1453              try {
1454 <                Thread.sleep(SMALL_DELAY_MS);
1454 >                delay(SMALL_DELAY_MS);
1455                  done = true;
1456              } catch (InterruptedException ok) {}
1457              return Boolean.TRUE;
# Line 814 | Line 1464 | public class JSR166TestCase extends Test
1464      public abstract class CheckedRecursiveAction extends RecursiveAction {
1465          protected abstract void realCompute() throws Throwable;
1466  
1467 <        public final void compute() {
1467 >        @Override protected final void compute() {
1468              try {
1469                  realCompute();
1470 <            } catch (Throwable t) {
1471 <                threadUnexpectedException(t);
1470 >            } catch (Throwable fail) {
1471 >                threadUnexpectedException(fail);
1472              }
1473          }
1474      }
# Line 829 | Line 1479 | public class JSR166TestCase extends Test
1479      public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1480          protected abstract T realCompute() throws Throwable;
1481  
1482 <        public final T compute() {
1482 >        @Override protected final T compute() {
1483              try {
1484                  return realCompute();
1485 <            } catch (Throwable t) {
1486 <                threadUnexpectedException(t);
1485 >            } catch (Throwable fail) {
1486 >                threadUnexpectedException(fail);
1487                  return null;
1488              }
1489          }
# Line 847 | Line 1497 | public class JSR166TestCase extends Test
1497                                        ThreadPoolExecutor executor) {}
1498      }
1499  
1500 +    /**
1501 +     * A CyclicBarrier that uses timed await and fails with
1502 +     * AssertionFailedErrors instead of throwing checked exceptions.
1503 +     */
1504 +    public class CheckedBarrier extends CyclicBarrier {
1505 +        public CheckedBarrier(int parties) { super(parties); }
1506 +
1507 +        public int await() {
1508 +            try {
1509 +                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1510 +            } catch (TimeoutException timedOut) {
1511 +                throw new AssertionFailedError("timed out");
1512 +            } catch (Exception fail) {
1513 +                AssertionFailedError afe =
1514 +                    new AssertionFailedError("Unexpected exception: " + fail);
1515 +                afe.initCause(fail);
1516 +                throw afe;
1517 +            }
1518 +        }
1519 +    }
1520 +
1521 +    void checkEmpty(BlockingQueue q) {
1522 +        try {
1523 +            assertTrue(q.isEmpty());
1524 +            assertEquals(0, q.size());
1525 +            assertNull(q.peek());
1526 +            assertNull(q.poll());
1527 +            assertNull(q.poll(0, MILLISECONDS));
1528 +            assertEquals(q.toString(), "[]");
1529 +            assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1530 +            assertFalse(q.iterator().hasNext());
1531 +            try {
1532 +                q.element();
1533 +                shouldThrow();
1534 +            } catch (NoSuchElementException success) {}
1535 +            try {
1536 +                q.iterator().next();
1537 +                shouldThrow();
1538 +            } catch (NoSuchElementException success) {}
1539 +            try {
1540 +                q.remove();
1541 +                shouldThrow();
1542 +            } catch (NoSuchElementException success) {}
1543 +        } catch (InterruptedException fail) { threadUnexpectedException(fail); }
1544 +    }
1545 +
1546 +    void assertSerialEquals(Object x, Object y) {
1547 +        assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1548 +    }
1549 +
1550 +    void assertNotSerialEquals(Object x, Object y) {
1551 +        assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1552 +    }
1553 +
1554 +    byte[] serialBytes(Object o) {
1555 +        try {
1556 +            ByteArrayOutputStream bos = new ByteArrayOutputStream();
1557 +            ObjectOutputStream oos = new ObjectOutputStream(bos);
1558 +            oos.writeObject(o);
1559 +            oos.flush();
1560 +            oos.close();
1561 +            return bos.toByteArray();
1562 +        } catch (Throwable fail) {
1563 +            threadUnexpectedException(fail);
1564 +            return new byte[0];
1565 +        }
1566 +    }
1567 +
1568 +    @SuppressWarnings("unchecked")
1569 +    <T> T serialClone(T o) {
1570 +        try {
1571 +            ObjectInputStream ois = new ObjectInputStream
1572 +                (new ByteArrayInputStream(serialBytes(o)));
1573 +            T clone = (T) ois.readObject();
1574 +            assertSame(o.getClass(), clone.getClass());
1575 +            return clone;
1576 +        } catch (Throwable fail) {
1577 +            threadUnexpectedException(fail);
1578 +            return null;
1579 +        }
1580 +    }
1581 +
1582 +    public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1583 +                             Runnable... throwingActions) {
1584 +        for (Runnable throwingAction : throwingActions) {
1585 +            boolean threw = false;
1586 +            try { throwingAction.run(); }
1587 +            catch (Throwable t) {
1588 +                threw = true;
1589 +                if (!expectedExceptionClass.isInstance(t)) {
1590 +                    AssertionFailedError afe =
1591 +                        new AssertionFailedError
1592 +                        ("Expected " + expectedExceptionClass.getName() +
1593 +                         ", got " + t.getClass().getName());
1594 +                    afe.initCause(t);
1595 +                    threadUnexpectedException(afe);
1596 +                }
1597 +            }
1598 +            if (!threw)
1599 +                shouldThrow(expectedExceptionClass.getName());
1600 +        }
1601 +    }
1602 +
1603 +    public void assertIteratorExhausted(Iterator<?> it) {
1604 +        try {
1605 +            it.next();
1606 +            shouldThrow();
1607 +        } catch (NoSuchElementException success) {}
1608 +        assertFalse(it.hasNext());
1609 +    }
1610   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines