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.35 by jsr166, Mon Aug 3 19:07:51 2009 UTC vs.
Revision 1.122 by jsr166, Wed Dec 31 16:44:02 2014 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.*;
10 > import java.io.ByteArrayInputStream;
11 > import java.io.ByteArrayOutputStream;
12 > import java.io.ObjectInputStream;
13 > import java.io.ObjectOutputStream;
14 > import java.lang.management.ManagementFactory;
15 > import java.lang.management.ThreadInfo;
16 > import java.lang.reflect.Method;
17 > import java.util.ArrayList;
18 > import java.util.Arrays;
19 > import java.util.Date;
20 > import java.util.Enumeration;
21 > import java.util.List;
22 > import java.util.NoSuchElementException;
23 > import java.util.PropertyPermission;
24   import java.util.concurrent.*;
25 < import java.io.*;
26 < import java.security.*;
25 > import java.util.concurrent.atomic.AtomicReference;
26 > import static java.util.concurrent.TimeUnit.MILLISECONDS;
27 > import static java.util.concurrent.TimeUnit.NANOSECONDS;
28 > import java.util.regex.Pattern;
29 > import java.security.CodeSource;
30 > import java.security.Permission;
31 > import java.security.PermissionCollection;
32 > import java.security.Permissions;
33 > import java.security.Policy;
34 > import java.security.ProtectionDomain;
35 > import java.security.SecurityPermission;
36  
37   /**
38   * Base class for JSR166 Junit TCK tests.  Defines some constants,
# Line 25 | Line 47 | import java.security.*;
47   * <li> All assertions in code running in generated threads must use
48   * the forms {@link #threadFail}, {@link #threadAssertTrue}, {@link
49   * #threadAssertEquals}, or {@link #threadAssertNull}, (not
50 < * <tt>fail</tt>, <tt>assertTrue</tt>, etc.) It is OK (but not
50 > * {@code fail}, {@code assertTrue}, etc.) It is OK (but not
51   * particularly recommended) for other code to use these forms too.
52   * Only the most typically used JUnit assertion methods are defined
53   * this way, but enough to live with.</li>
54   *
55   * <li> If you override {@link #setUp} or {@link #tearDown}, make sure
56 < * to invoke <tt>super.setUp</tt> and <tt>super.tearDown</tt> within
56 > * to invoke {@code super.setUp} and {@code super.tearDown} within
57   * them. These methods are used to clear and check for thread
58   * assertion failures.</li>
59   *
60 < * <li>All delays and timeouts must use one of the constants <tt>
61 < * SHORT_DELAY_MS</tt>, <tt> SMALL_DELAY_MS</tt>, <tt> MEDIUM_DELAY_MS</tt>,
62 < * <tt> LONG_DELAY_MS</tt>. The idea here is that a SHORT is always
60 > * <li>All delays and timeouts must use one of the constants {@code
61 > * SHORT_DELAY_MS}, {@code SMALL_DELAY_MS}, {@code MEDIUM_DELAY_MS},
62 > * {@code LONG_DELAY_MS}. The idea here is that a SHORT is always
63   * discriminable from zero time, and always allows enough time for the
64   * small amounts of computation (creating a thread, calling a few
65   * methods, etc) needed to reach a timeout point. Similarly, a SMALL
# Line 47 | Line 69 | import java.security.*;
69   * in one spot to rerun tests on slower platforms.</li>
70   *
71   * <li> All threads generated must be joined inside each test case
72 < * method (or <tt>fail</tt> to do so) before returning from the
73 < * method. The <tt> joinPool</tt> method can be used to do this when
72 > * method (or {@code fail} to do so) before returning from the
73 > * method. The {@code joinPool} method can be used to do this when
74   * using Executors.</li>
75   *
76   * </ol>
77   *
78 < * <p> <b>Other notes</b>
78 > * <p><b>Other notes</b>
79   * <ul>
80   *
81   * <li> Usually, there is one testcase method per JSR166 method
# Line 80 | Line 102 | import java.security.*;
102   * any particular package to simplify things for people integrating
103   * them in TCK test suites.</li>
104   *
105 < * <li> As a convenience, the <tt>main</tt> of this class (JSR166TestCase)
105 > * <li> As a convenience, the {@code main} of this class (JSR166TestCase)
106   * runs all JSR166 unit tests.</li>
107   *
108   * </ul>
109   */
110   public class JSR166TestCase extends TestCase {
111 +    private static final boolean useSecurityManager =
112 +        Boolean.getBoolean("jsr166.useSecurityManager");
113 +
114 +    protected static final boolean expensiveTests =
115 +        Boolean.getBoolean("jsr166.expensiveTests");
116 +
117 +    /**
118 +     * If true, also run tests that are not part of the official tck
119 +     * because they test unspecified implementation details.
120 +     */
121 +    protected static final boolean testImplementationDetails =
122 +        Boolean.getBoolean("jsr166.testImplementationDetails");
123 +
124 +    /**
125 +     * If true, report on stdout all "slow" tests, that is, ones that
126 +     * take more than profileThreshold milliseconds to execute.
127 +     */
128 +    private static final boolean profileTests =
129 +        Boolean.getBoolean("jsr166.profileTests");
130 +
131 +    /**
132 +     * The number of milliseconds that tests are permitted for
133 +     * execution without being reported, when profileTests is set.
134 +     */
135 +    private static final long profileThreshold =
136 +        Long.getLong("jsr166.profileThreshold", 100);
137 +
138      /**
139 <     * Runs all JSR166 unit tests using junit.textui.TestRunner
139 >     * The number of repetitions per test (for tickling rare bugs).
140       */
141 <    public static void main (String[] args) {
142 <        int iters = 1;
143 <        if (args.length > 0)
144 <            iters = Integer.parseInt(args[0]);
141 >    private static final int runsPerTest =
142 >        Integer.getInteger("jsr166.runsPerTest", 1);
143 >
144 >    /**
145 >     * A filter for tests to run, matching strings of the form
146 >     * methodName(className), e.g. "testInvokeAll5(ForkJoinPoolTest)"
147 >     * Usefully combined with jsr166.runsPerTest.
148 >     */
149 >    private static final Pattern methodFilter = methodFilter();
150 >
151 >    private static Pattern methodFilter() {
152 >        String regex = System.getProperty("jsr166.methodFilter");
153 >        return (regex == null) ? null : Pattern.compile(regex);
154 >    }
155 >
156 >    protected void runTest() throws Throwable {
157 >        if (methodFilter == null
158 >            || methodFilter.matcher(toString()).find()) {
159 >            for (int i = 0; i < runsPerTest; i++) {
160 >                if (profileTests)
161 >                    runTestProfiled();
162 >                else
163 >                    super.runTest();
164 >            }
165 >        }
166 >    }
167 >
168 >    protected void runTestProfiled() throws Throwable {
169 >        // Warmup run, notably to trigger all needed classloading.
170 >        super.runTest();
171 >        long t0 = System.nanoTime();
172 >        try {
173 >            super.runTest();
174 >        } finally {
175 >            long elapsedMillis = millisElapsedSince(t0);
176 >            if (elapsedMillis >= profileThreshold)
177 >                System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
178 >        }
179 >    }
180 >
181 >    /**
182 >     * Runs all JSR166 unit tests using junit.textui.TestRunner.
183 >     * Optional command line arg provides the number of iterations to
184 >     * repeat running the tests.
185 >     */
186 >    public static void main(String[] args) {
187 >        if (useSecurityManager) {
188 >            System.err.println("Setting a permissive security manager");
189 >            Policy.setPolicy(permissivePolicy());
190 >            System.setSecurityManager(new SecurityManager());
191 >        }
192 >        int iters = (args.length == 0) ? 1 : Integer.parseInt(args[0]);
193 >
194          Test s = suite();
195          for (int i = 0; i < iters; ++i) {
196 <            junit.textui.TestRunner.run (s);
196 >            junit.textui.TestRunner.run(s);
197              System.gc();
198              System.runFinalization();
199          }
200          System.exit(0);
201      }
202  
203 <    /**
204 <     * Collects all JSR166 unit tests as one suite
205 <     */
206 <    public static Test suite ( ) {
207 <        TestSuite suite = new TestSuite("JSR166 Unit Tests");
203 >    public static TestSuite newTestSuite(Object... suiteOrClasses) {
204 >        TestSuite suite = new TestSuite();
205 >        for (Object suiteOrClass : suiteOrClasses) {
206 >            if (suiteOrClass instanceof TestSuite)
207 >                suite.addTest((TestSuite) suiteOrClass);
208 >            else if (suiteOrClass instanceof Class)
209 >                suite.addTest(new TestSuite((Class<?>) suiteOrClass));
210 >            else
211 >                throw new ClassCastException("not a test suite or class");
212 >        }
213 >        return suite;
214 >    }
215  
216 <        suite.addTest(new TestSuite(ForkJoinPoolTest.class));
217 <        suite.addTest(new TestSuite(ForkJoinTaskTest.class));
218 <        suite.addTest(new TestSuite(RecursiveActionTest.class));
219 <        suite.addTest(new TestSuite(RecursiveTaskTest.class));
220 <        suite.addTest(new TestSuite(LinkedTransferQueueTest.class));
221 <        suite.addTest(new TestSuite(PhaserTest.class));
222 <        suite.addTest(new TestSuite(ThreadLocalRandomTest.class));
223 <        suite.addTest(new TestSuite(AbstractExecutorServiceTest.class));
224 <        suite.addTest(new TestSuite(AbstractQueueTest.class));
225 <        suite.addTest(new TestSuite(AbstractQueuedSynchronizerTest.class));
226 <        suite.addTest(new TestSuite(AbstractQueuedLongSynchronizerTest.class));
227 <        suite.addTest(new TestSuite(ArrayBlockingQueueTest.class));
228 <        suite.addTest(new TestSuite(ArrayDequeTest.class));
229 <        suite.addTest(new TestSuite(AtomicBooleanTest.class));
230 <        suite.addTest(new TestSuite(AtomicIntegerArrayTest.class));
231 <        suite.addTest(new TestSuite(AtomicIntegerFieldUpdaterTest.class));
232 <        suite.addTest(new TestSuite(AtomicIntegerTest.class));
233 <        suite.addTest(new TestSuite(AtomicLongArrayTest.class));
234 <        suite.addTest(new TestSuite(AtomicLongFieldUpdaterTest.class));
235 <        suite.addTest(new TestSuite(AtomicLongTest.class));
236 <        suite.addTest(new TestSuite(AtomicMarkableReferenceTest.class));
237 <        suite.addTest(new TestSuite(AtomicReferenceArrayTest.class));
238 <        suite.addTest(new TestSuite(AtomicReferenceFieldUpdaterTest.class));
239 <        suite.addTest(new TestSuite(AtomicReferenceTest.class));
240 <        suite.addTest(new TestSuite(AtomicStampedReferenceTest.class));
241 <        suite.addTest(new TestSuite(ConcurrentHashMapTest.class));
242 <        suite.addTest(new TestSuite(ConcurrentLinkedQueueTest.class));
243 <        suite.addTest(new TestSuite(ConcurrentSkipListMapTest.class));
244 <        suite.addTest(new TestSuite(ConcurrentSkipListSubMapTest.class));
245 <        suite.addTest(new TestSuite(ConcurrentSkipListSetTest.class));
246 <        suite.addTest(new TestSuite(ConcurrentSkipListSubSetTest.class));
247 <        suite.addTest(new TestSuite(CopyOnWriteArrayListTest.class));
248 <        suite.addTest(new TestSuite(CopyOnWriteArraySetTest.class));
249 <        suite.addTest(new TestSuite(CountDownLatchTest.class));
250 <        suite.addTest(new TestSuite(CyclicBarrierTest.class));
251 <        suite.addTest(new TestSuite(DelayQueueTest.class));
252 <        suite.addTest(new TestSuite(EntryTest.class));
253 <        suite.addTest(new TestSuite(ExchangerTest.class));
254 <        suite.addTest(new TestSuite(ExecutorsTest.class));
255 <        suite.addTest(new TestSuite(ExecutorCompletionServiceTest.class));
256 <        suite.addTest(new TestSuite(FutureTaskTest.class));
257 <        suite.addTest(new TestSuite(LinkedBlockingDequeTest.class));
258 <        suite.addTest(new TestSuite(LinkedBlockingQueueTest.class));
259 <        suite.addTest(new TestSuite(LinkedListTest.class));
260 <        suite.addTest(new TestSuite(LockSupportTest.class));
261 <        suite.addTest(new TestSuite(PriorityBlockingQueueTest.class));
262 <        suite.addTest(new TestSuite(PriorityQueueTest.class));
263 <        suite.addTest(new TestSuite(ReentrantLockTest.class));
264 <        suite.addTest(new TestSuite(ReentrantReadWriteLockTest.class));
265 <        suite.addTest(new TestSuite(ScheduledExecutorTest.class));
266 <        suite.addTest(new TestSuite(ScheduledExecutorSubclassTest.class));
267 <        suite.addTest(new TestSuite(SemaphoreTest.class));
268 <        suite.addTest(new TestSuite(SynchronousQueueTest.class));
269 <        suite.addTest(new TestSuite(SystemTest.class));
270 <        suite.addTest(new TestSuite(ThreadLocalTest.class));
271 <        suite.addTest(new TestSuite(ThreadPoolExecutorTest.class));
272 <        suite.addTest(new TestSuite(ThreadPoolExecutorSubclassTest.class));
273 <        suite.addTest(new TestSuite(ThreadTest.class));
274 <        suite.addTest(new TestSuite(TimeUnitTest.class));
275 <        suite.addTest(new TestSuite(TreeMapTest.class));
276 <        suite.addTest(new TestSuite(TreeSetTest.class));
277 <        suite.addTest(new TestSuite(TreeSubMapTest.class));
278 <        suite.addTest(new TestSuite(TreeSubSetTest.class));
216 >    public static void addNamedTestClasses(TestSuite suite,
217 >                                           String... testClassNames) {
218 >        for (String testClassName : testClassNames) {
219 >            try {
220 >                Class<?> testClass = Class.forName(testClassName);
221 >                Method m = testClass.getDeclaredMethod("suite",
222 >                                                       new Class<?>[0]);
223 >                suite.addTest(newTestSuite((Test)m.invoke(null)));
224 >            } catch (Exception e) {
225 >                throw new Error("Missing test class", e);
226 >            }
227 >        }
228 >    }
229 >
230 >    public static final double JAVA_CLASS_VERSION;
231 >    public static final String JAVA_SPECIFICATION_VERSION;
232 >    static {
233 >        try {
234 >            JAVA_CLASS_VERSION = java.security.AccessController.doPrivileged(
235 >                new java.security.PrivilegedAction<Double>() {
236 >                public Double run() {
237 >                    return Double.valueOf(System.getProperty("java.class.version"));}});
238 >            JAVA_SPECIFICATION_VERSION = java.security.AccessController.doPrivileged(
239 >                new java.security.PrivilegedAction<String>() {
240 >                public String run() {
241 >                    return System.getProperty("java.specification.version");}});
242 >        } catch (Throwable t) {
243 >            throw new Error(t);
244 >        }
245 >    }
246 >
247 >    public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
248 >    public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
249 >    public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
250 >    public static boolean atLeastJava9() {
251 >        // As of 2014-05, java9 still uses 52.0 class file version
252 >        return JAVA_SPECIFICATION_VERSION.startsWith("1.9");
253 >    }
254 >
255 >    /**
256 >     * Collects all JSR166 unit tests as one suite.
257 >     */
258 >    public static Test suite() {
259 >        // Java7+ test classes
260 >        TestSuite suite = newTestSuite(
261 >            ForkJoinPoolTest.suite(),
262 >            ForkJoinTaskTest.suite(),
263 >            RecursiveActionTest.suite(),
264 >            RecursiveTaskTest.suite(),
265 >            LinkedTransferQueueTest.suite(),
266 >            PhaserTest.suite(),
267 >            ThreadLocalRandomTest.suite(),
268 >            AbstractExecutorServiceTest.suite(),
269 >            AbstractQueueTest.suite(),
270 >            AbstractQueuedSynchronizerTest.suite(),
271 >            AbstractQueuedLongSynchronizerTest.suite(),
272 >            ArrayBlockingQueueTest.suite(),
273 >            ArrayDequeTest.suite(),
274 >            AtomicBooleanTest.suite(),
275 >            AtomicIntegerArrayTest.suite(),
276 >            AtomicIntegerFieldUpdaterTest.suite(),
277 >            AtomicIntegerTest.suite(),
278 >            AtomicLongArrayTest.suite(),
279 >            AtomicLongFieldUpdaterTest.suite(),
280 >            AtomicLongTest.suite(),
281 >            AtomicMarkableReferenceTest.suite(),
282 >            AtomicReferenceArrayTest.suite(),
283 >            AtomicReferenceFieldUpdaterTest.suite(),
284 >            AtomicReferenceTest.suite(),
285 >            AtomicStampedReferenceTest.suite(),
286 >            ConcurrentHashMapTest.suite(),
287 >            ConcurrentLinkedDequeTest.suite(),
288 >            ConcurrentLinkedQueueTest.suite(),
289 >            ConcurrentSkipListMapTest.suite(),
290 >            ConcurrentSkipListSubMapTest.suite(),
291 >            ConcurrentSkipListSetTest.suite(),
292 >            ConcurrentSkipListSubSetTest.suite(),
293 >            CopyOnWriteArrayListTest.suite(),
294 >            CopyOnWriteArraySetTest.suite(),
295 >            CountDownLatchTest.suite(),
296 >            CyclicBarrierTest.suite(),
297 >            DelayQueueTest.suite(),
298 >            EntryTest.suite(),
299 >            ExchangerTest.suite(),
300 >            ExecutorsTest.suite(),
301 >            ExecutorCompletionServiceTest.suite(),
302 >            FutureTaskTest.suite(),
303 >            LinkedBlockingDequeTest.suite(),
304 >            LinkedBlockingQueueTest.suite(),
305 >            LinkedListTest.suite(),
306 >            LockSupportTest.suite(),
307 >            PriorityBlockingQueueTest.suite(),
308 >            PriorityQueueTest.suite(),
309 >            ReentrantLockTest.suite(),
310 >            ReentrantReadWriteLockTest.suite(),
311 >            ScheduledExecutorTest.suite(),
312 >            ScheduledExecutorSubclassTest.suite(),
313 >            SemaphoreTest.suite(),
314 >            SynchronousQueueTest.suite(),
315 >            SystemTest.suite(),
316 >            ThreadLocalTest.suite(),
317 >            ThreadPoolExecutorTest.suite(),
318 >            ThreadPoolExecutorSubclassTest.suite(),
319 >            ThreadTest.suite(),
320 >            TimeUnitTest.suite(),
321 >            TreeMapTest.suite(),
322 >            TreeSetTest.suite(),
323 >            TreeSubMapTest.suite(),
324 >            TreeSubSetTest.suite());
325 >
326 >        // Java8+ test classes
327 >        if (atLeastJava8()) {
328 >            String[] java8TestClassNames = {
329 >                "Atomic8Test",
330 >                "CompletableFutureTest",
331 >                "ConcurrentHashMap8Test",
332 >                "CountedCompleterTest",
333 >                "DoubleAccumulatorTest",
334 >                "DoubleAdderTest",
335 >                "ForkJoinPool8Test",
336 >                "ForkJoinTask8Test",
337 >                "LongAccumulatorTest",
338 >                "LongAdderTest",
339 >                "SplittableRandomTest",
340 >                "StampedLockTest",
341 >                "ThreadLocalRandom8Test",
342 >            };
343 >            addNamedTestClasses(suite, java8TestClassNames);
344 >        }
345 >
346 >        // Java9+ test classes
347 >        if (atLeastJava9()) {
348 >            String[] java9TestClassNames = {
349 >                "ThreadPoolExecutor9Test",
350 >            };
351 >            addNamedTestClasses(suite, java9TestClassNames);
352 >        }
353  
354          return suite;
355      }
356  
357 +    // Delays for timing-dependent tests, in milliseconds.
358  
359      public static long SHORT_DELAY_MS;
360      public static long SMALL_DELAY_MS;
361      public static long MEDIUM_DELAY_MS;
362      public static long LONG_DELAY_MS;
363  
184
364      /**
365       * Returns the shortest timed delay. This could
366       * be reimplemented to use for example a Property.
# Line 190 | Line 369 | public class JSR166TestCase extends Test
369          return 50;
370      }
371  
193
372      /**
373       * Sets delays as multiples of SHORT_DELAY.
374       */
375 <    protected  void setDelays() {
375 >    protected void setDelays() {
376          SHORT_DELAY_MS = getShortDelay();
377 <        SMALL_DELAY_MS = SHORT_DELAY_MS * 5;
377 >        SMALL_DELAY_MS  = SHORT_DELAY_MS * 5;
378          MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
379 <        LONG_DELAY_MS = SHORT_DELAY_MS * 50;
379 >        LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
380      }
381  
382      /**
383 <     * Flag set true if any threadAssert methods fail
383 >     * Returns a timeout in milliseconds to be used in tests that
384 >     * verify that operations block or time out.
385       */
386 <    volatile boolean threadFailed;
386 >    long timeoutMillis() {
387 >        return SHORT_DELAY_MS / 4;
388 >    }
389 >
390 >    /**
391 >     * Returns a new Date instance representing a time delayMillis
392 >     * milliseconds in the future.
393 >     */
394 >    Date delayedDate(long delayMillis) {
395 >        return new Date(System.currentTimeMillis() + delayMillis);
396 >    }
397  
398      /**
399 <     * Initializes test to indicate that no thread assertions have failed
399 >     * The first exception encountered if any threadAssertXXX method fails.
400       */
401 +    private final AtomicReference<Throwable> threadFailure
402 +        = new AtomicReference<Throwable>(null);
403 +
404 +    /**
405 +     * Records an exception so that it can be rethrown later in the test
406 +     * harness thread, triggering a test case failure.  Only the first
407 +     * failure is recorded; subsequent calls to this method from within
408 +     * the same test have no effect.
409 +     */
410 +    public void threadRecordFailure(Throwable t) {
411 +        threadFailure.compareAndSet(null, t);
412 +    }
413 +
414      public void setUp() {
415          setDelays();
214        threadFailed = false;
416      }
417  
418      /**
419 <     * Triggers test case failure if any thread assertions have failed
419 >     * Extra checks that get done for all test cases.
420 >     *
421 >     * Triggers test case failure if any thread assertions have failed,
422 >     * by rethrowing, in the test harness thread, any exception recorded
423 >     * earlier by threadRecordFailure.
424 >     *
425 >     * Triggers test case failure if interrupt status is set in the main thread.
426 >     */
427 >    public void tearDown() throws Exception {
428 >        Throwable t = threadFailure.getAndSet(null);
429 >        if (t != null) {
430 >            if (t instanceof Error)
431 >                throw (Error) t;
432 >            else if (t instanceof RuntimeException)
433 >                throw (RuntimeException) t;
434 >            else if (t instanceof Exception)
435 >                throw (Exception) t;
436 >            else {
437 >                AssertionFailedError afe =
438 >                    new AssertionFailedError(t.toString());
439 >                afe.initCause(t);
440 >                throw afe;
441 >            }
442 >        }
443 >
444 >        if (Thread.interrupted())
445 >            throw new AssertionFailedError("interrupt status set in main thread");
446 >
447 >        checkForkJoinPoolThreadLeaks();
448 >    }
449 >
450 >    /**
451 >     * Find missing try { ... } finally { joinPool(e); }
452       */
453 <    public void tearDown() {
454 <        assertFalse(threadFailed);
453 >    void checkForkJoinPoolThreadLeaks() throws InterruptedException {
454 >        Thread[] survivors = new Thread[5];
455 >        int count = Thread.enumerate(survivors);
456 >        for (int i = 0; i < count; i++) {
457 >            Thread thread = survivors[i];
458 >            String name = thread.getName();
459 >            if (name.startsWith("ForkJoinPool-")) {
460 >                // give thread some time to terminate
461 >                thread.join(LONG_DELAY_MS);
462 >                if (!thread.isAlive()) continue;
463 >                thread.stop();
464 >                throw new AssertionFailedError
465 >                    (String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n",
466 >                                   toString(), name));
467 >            }
468 >        }
469      }
470  
471      /**
472 <     * Fail, also setting status to indicate current testcase should fail
472 >     * Just like fail(reason), but additionally recording (using
473 >     * threadRecordFailure) any AssertionFailedError thrown, so that
474 >     * the current testcase will fail.
475       */
476      public void threadFail(String reason) {
477 <        threadFailed = true;
478 <        fail(reason);
477 >        try {
478 >            fail(reason);
479 >        } catch (AssertionFailedError t) {
480 >            threadRecordFailure(t);
481 >            fail(reason);
482 >        }
483      }
484  
485      /**
486 <     * If expression not true, set status to indicate current testcase
487 <     * should fail
486 >     * Just like assertTrue(b), but additionally recording (using
487 >     * threadRecordFailure) any AssertionFailedError thrown, so that
488 >     * the current testcase will fail.
489       */
490      public void threadAssertTrue(boolean b) {
491 <        if (!b) {
238 <            threadFailed = true;
491 >        try {
492              assertTrue(b);
493 +        } catch (AssertionFailedError t) {
494 +            threadRecordFailure(t);
495 +            throw t;
496          }
497      }
498  
499      /**
500 <     * If expression not false, set status to indicate current testcase
501 <     * should fail
500 >     * Just like assertFalse(b), but additionally recording (using
501 >     * threadRecordFailure) any AssertionFailedError thrown, so that
502 >     * the current testcase will fail.
503       */
504      public void threadAssertFalse(boolean b) {
505 <        if (b) {
249 <            threadFailed = true;
505 >        try {
506              assertFalse(b);
507 +        } catch (AssertionFailedError t) {
508 +            threadRecordFailure(t);
509 +            throw t;
510          }
511      }
512  
513      /**
514 <     * If argument not null, set status to indicate current testcase
515 <     * should fail
514 >     * Just like assertNull(x), but additionally recording (using
515 >     * threadRecordFailure) any AssertionFailedError thrown, so that
516 >     * the current testcase will fail.
517       */
518      public void threadAssertNull(Object x) {
519 <        if (x != null) {
260 <            threadFailed = true;
519 >        try {
520              assertNull(x);
521 +        } catch (AssertionFailedError t) {
522 +            threadRecordFailure(t);
523 +            throw t;
524          }
525      }
526  
527      /**
528 <     * If arguments not equal, set status to indicate current testcase
529 <     * should fail
528 >     * Just like assertEquals(x, y), but additionally recording (using
529 >     * threadRecordFailure) any AssertionFailedError thrown, so that
530 >     * the current testcase will fail.
531       */
532      public void threadAssertEquals(long x, long y) {
533 <        if (x != y) {
271 <            threadFailed = true;
533 >        try {
534              assertEquals(x, y);
535 +        } catch (AssertionFailedError t) {
536 +            threadRecordFailure(t);
537 +            throw t;
538          }
539      }
540  
541      /**
542 <     * If arguments not equal, set status to indicate current testcase
543 <     * should fail
542 >     * Just like assertEquals(x, y), but additionally recording (using
543 >     * threadRecordFailure) any AssertionFailedError thrown, so that
544 >     * the current testcase will fail.
545       */
546      public void threadAssertEquals(Object x, Object y) {
547 <        if (x != y && (x == null || !x.equals(y))) {
282 <            threadFailed = true;
547 >        try {
548              assertEquals(x, y);
549 +        } catch (AssertionFailedError t) {
550 +            threadRecordFailure(t);
551 +            throw t;
552 +        } catch (Throwable t) {
553 +            threadUnexpectedException(t);
554          }
555      }
556  
557      /**
558 <     * threadFail with message "should throw exception"
558 >     * Just like assertSame(x, y), but additionally recording (using
559 >     * threadRecordFailure) any AssertionFailedError thrown, so that
560 >     * the current testcase will fail.
561       */
562 <    public void threadShouldThrow() {
562 >    public void threadAssertSame(Object x, Object y) {
563          try {
564 <            threadFailed = true;
565 <            fail("should throw exception");
566 <        } catch (AssertionFailedError e) {
567 <            e.printStackTrace();
296 <            throw e;
564 >            assertSame(x, y);
565 >        } catch (AssertionFailedError t) {
566 >            threadRecordFailure(t);
567 >            throw t;
568          }
569      }
570  
571      /**
572 <     * threadFail with message "Unexpected exception"
572 >     * Calls threadFail with message "should throw exception".
573       */
574 <    public void threadUnexpectedException() {
575 <        threadFailed = true;
305 <        fail("Unexpected exception");
574 >    public void threadShouldThrow() {
575 >        threadFail("should throw exception");
576      }
577  
578      /**
579 <     * threadFail with message "Unexpected exception", with argument
579 >     * Calls threadFail with message "should throw" + exceptionName.
580       */
581 <    public void threadUnexpectedException(Throwable ex) {
582 <        threadFailed = true;
583 <        ex.printStackTrace();
584 <        fail("Unexpected exception: " + ex);
581 >    public void threadShouldThrow(String exceptionName) {
582 >        threadFail("should throw " + exceptionName);
583 >    }
584 >
585 >    /**
586 >     * Records the given exception using {@link #threadRecordFailure},
587 >     * then rethrows the exception, wrapping it in an
588 >     * AssertionFailedError if necessary.
589 >     */
590 >    public void threadUnexpectedException(Throwable t) {
591 >        threadRecordFailure(t);
592 >        t.printStackTrace();
593 >        if (t instanceof RuntimeException)
594 >            throw (RuntimeException) t;
595 >        else if (t instanceof Error)
596 >            throw (Error) t;
597 >        else {
598 >            AssertionFailedError afe =
599 >                new AssertionFailedError("unexpected exception: " + t);
600 >            afe.initCause(t);
601 >            throw afe;
602 >        }
603      }
604  
605      /**
606 <     * Wait out termination of a thread pool or fail doing so
606 >     * Delays, via Thread.sleep, for the given millisecond delay, but
607 >     * if the sleep is shorter than specified, may re-sleep or yield
608 >     * until time elapses.
609       */
610 <    public void joinPool(ExecutorService exec) {
610 >    static void delay(long millis) throws InterruptedException {
611 >        long startTime = System.nanoTime();
612 >        long ns = millis * 1000 * 1000;
613 >        for (;;) {
614 >            if (millis > 0L)
615 >                Thread.sleep(millis);
616 >            else // too short to sleep
617 >                Thread.yield();
618 >            long d = ns - (System.nanoTime() - startTime);
619 >            if (d > 0L)
620 >                millis = d / (1000 * 1000);
621 >            else
622 >                break;
623 >        }
624 >    }
625 >
626 >    /**
627 >     * Waits out termination of a thread pool or fails doing so.
628 >     */
629 >    void joinPool(ExecutorService exec) {
630          try {
631              exec.shutdown();
632 <            assertTrue(exec.awaitTermination(LONG_DELAY_MS, TimeUnit.MILLISECONDS));
632 >            if (!exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS))
633 >                fail("ExecutorService " + exec +
634 >                     " did not terminate in a timely manner");
635          } catch (SecurityException ok) {
636              // Allowed in case test doesn't have privs
637          } catch (InterruptedException ie) {
638 <            fail("Unexpected exception");
638 >            fail("Unexpected InterruptedException");
639 >        }
640 >    }
641 >
642 >    /**
643 >     * A debugging tool to print all stack traces, as jstack does.
644 >     */
645 >    static void printAllStackTraces() {
646 >        for (ThreadInfo info :
647 >                 ManagementFactory.getThreadMXBean()
648 >                 .dumpAllThreads(true, true))
649 >            System.err.print(info);
650 >    }
651 >
652 >    /**
653 >     * Checks that thread does not terminate within the default
654 >     * millisecond delay of {@code timeoutMillis()}.
655 >     */
656 >    void assertThreadStaysAlive(Thread thread) {
657 >        assertThreadStaysAlive(thread, timeoutMillis());
658 >    }
659 >
660 >    /**
661 >     * Checks that thread does not terminate within the given millisecond delay.
662 >     */
663 >    void assertThreadStaysAlive(Thread thread, long millis) {
664 >        try {
665 >            // No need to optimize the failing case via Thread.join.
666 >            delay(millis);
667 >            assertTrue(thread.isAlive());
668 >        } catch (InterruptedException ie) {
669 >            fail("Unexpected InterruptedException");
670          }
671      }
672  
673 +    /**
674 +     * Checks that the threads do not terminate within the default
675 +     * millisecond delay of {@code timeoutMillis()}.
676 +     */
677 +    void assertThreadsStayAlive(Thread... threads) {
678 +        assertThreadsStayAlive(timeoutMillis(), threads);
679 +    }
680 +
681 +    /**
682 +     * Checks that the threads do not terminate within the given millisecond delay.
683 +     */
684 +    void assertThreadsStayAlive(long millis, Thread... threads) {
685 +        try {
686 +            // No need to optimize the failing case via Thread.join.
687 +            delay(millis);
688 +            for (Thread thread : threads)
689 +                assertTrue(thread.isAlive());
690 +        } catch (InterruptedException ie) {
691 +            fail("Unexpected InterruptedException");
692 +        }
693 +    }
694 +
695 +    /**
696 +     * Checks that future.get times out, with the default timeout of
697 +     * {@code timeoutMillis()}.
698 +     */
699 +    void assertFutureTimesOut(Future future) {
700 +        assertFutureTimesOut(future, timeoutMillis());
701 +    }
702 +
703 +    /**
704 +     * Checks that future.get times out, with the given millisecond timeout.
705 +     */
706 +    void assertFutureTimesOut(Future future, long timeoutMillis) {
707 +        long startTime = System.nanoTime();
708 +        try {
709 +            future.get(timeoutMillis, MILLISECONDS);
710 +            shouldThrow();
711 +        } catch (TimeoutException success) {
712 +        } catch (Exception e) {
713 +            threadUnexpectedException(e);
714 +        } finally { future.cancel(true); }
715 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
716 +    }
717  
718      /**
719 <     * fail with message "should throw exception"
719 >     * Fails with message "should throw exception".
720       */
721      public void shouldThrow() {
722          fail("Should throw exception");
723      }
724  
725      /**
726 <     * fail with message "Unexpected exception"
726 >     * Fails with message "should throw " + exceptionName.
727       */
728 <    public void unexpectedException() {
729 <        fail("Unexpected exception");
728 >    public void shouldThrow(String exceptionName) {
729 >        fail("Should throw " + exceptionName);
730      }
731  
346
732      /**
733       * The number of elements to place in collections, arrays, etc.
734       */
735 <    static final int SIZE = 20;
735 >    public static final int SIZE = 20;
736  
737      // Some convenient Integer constants
738  
739 <    static final Integer zero = new Integer(0);
740 <    static final Integer one = new Integer(1);
741 <    static final Integer two = new Integer(2);
742 <    static final Integer three  = new Integer(3);
743 <    static final Integer four  = new Integer(4);
744 <    static final Integer five  = new Integer(5);
745 <    static final Integer six = new Integer(6);
746 <    static final Integer seven = new Integer(7);
747 <    static final Integer eight = new Integer(8);
748 <    static final Integer nine = new Integer(9);
749 <    static final Integer m1  = new Integer(-1);
750 <    static final Integer m2  = new Integer(-2);
751 <    static final Integer m3  = new Integer(-3);
752 <    static final Integer m4 = new Integer(-4);
753 <    static final Integer m5 = new Integer(-5);
754 <    static final Integer m6 = new Integer(-6);
755 <    static final Integer m10 = new Integer(-10);
739 >    public static final Integer zero  = new Integer(0);
740 >    public static final Integer one   = new Integer(1);
741 >    public static final Integer two   = new Integer(2);
742 >    public static final Integer three = new Integer(3);
743 >    public static final Integer four  = new Integer(4);
744 >    public static final Integer five  = new Integer(5);
745 >    public static final Integer six   = new Integer(6);
746 >    public static final Integer seven = new Integer(7);
747 >    public static final Integer eight = new Integer(8);
748 >    public static final Integer nine  = new Integer(9);
749 >    public static final Integer m1  = new Integer(-1);
750 >    public static final Integer m2  = new Integer(-2);
751 >    public static final Integer m3  = new Integer(-3);
752 >    public static final Integer m4  = new Integer(-4);
753 >    public static final Integer m5  = new Integer(-5);
754 >    public static final Integer m6  = new Integer(-6);
755 >    public static final Integer m10 = new Integer(-10);
756 >
757 >    /**
758 >     * Runs Runnable r with a security policy that permits precisely
759 >     * the specified permissions.  If there is no current security
760 >     * manager, the runnable is run twice, both with and without a
761 >     * security manager.  We require that any security manager permit
762 >     * getPolicy/setPolicy.
763 >     */
764 >    public void runWithPermissions(Runnable r, Permission... permissions) {
765 >        SecurityManager sm = System.getSecurityManager();
766 >        if (sm == null) {
767 >            r.run();
768 >        }
769 >        runWithSecurityManagerWithPermissions(r, permissions);
770 >    }
771  
772 +    /**
773 +     * Runs Runnable r with a security policy that permits precisely
774 +     * the specified permissions.  If there is no current security
775 +     * manager, a temporary one is set for the duration of the
776 +     * Runnable.  We require that any security manager permit
777 +     * getPolicy/setPolicy.
778 +     */
779 +    public void runWithSecurityManagerWithPermissions(Runnable r,
780 +                                                      Permission... permissions) {
781 +        SecurityManager sm = System.getSecurityManager();
782 +        if (sm == null) {
783 +            Policy savedPolicy = Policy.getPolicy();
784 +            try {
785 +                Policy.setPolicy(permissivePolicy());
786 +                System.setSecurityManager(new SecurityManager());
787 +                runWithSecurityManagerWithPermissions(r, permissions);
788 +            } finally {
789 +                System.setSecurityManager(null);
790 +                Policy.setPolicy(savedPolicy);
791 +            }
792 +        } else {
793 +            Policy savedPolicy = Policy.getPolicy();
794 +            AdjustablePolicy policy = new AdjustablePolicy(permissions);
795 +            Policy.setPolicy(policy);
796 +
797 +            try {
798 +                r.run();
799 +            } finally {
800 +                policy.addPermission(new SecurityPermission("setPolicy"));
801 +                Policy.setPolicy(savedPolicy);
802 +            }
803 +        }
804 +    }
805 +
806 +    /**
807 +     * Runs a runnable without any permissions.
808 +     */
809 +    public void runWithoutPermissions(Runnable r) {
810 +        runWithPermissions(r);
811 +    }
812  
813      /**
814       * A security policy where new permissions can be dynamically added
815       * or all cleared.
816       */
817 <    static class AdjustablePolicy extends java.security.Policy {
817 >    public static class AdjustablePolicy extends java.security.Policy {
818          Permissions perms = new Permissions();
819 <        AdjustablePolicy() { }
819 >        AdjustablePolicy(Permission... permissions) {
820 >            for (Permission permission : permissions)
821 >                perms.add(permission);
822 >        }
823          void addPermission(Permission perm) { perms.add(perm); }
824          void clearPermissions() { perms = new Permissions(); }
825 <        public PermissionCollection getPermissions(CodeSource cs) {
826 <            return perms;
827 <        }
828 <        public PermissionCollection getPermissions(ProtectionDomain pd) {
829 <            return perms;
830 <        }
831 <        public boolean implies(ProtectionDomain pd, Permission p) {
832 <            return perms.implies(p);
833 <        }
834 <        public void refresh() {}
825 >        public PermissionCollection getPermissions(CodeSource cs) {
826 >            return perms;
827 >        }
828 >        public PermissionCollection getPermissions(ProtectionDomain pd) {
829 >            return perms;
830 >        }
831 >        public boolean implies(ProtectionDomain pd, Permission p) {
832 >            return perms.implies(p);
833 >        }
834 >        public void refresh() {}
835 >        public String toString() {
836 >            List<Permission> ps = new ArrayList<Permission>();
837 >            for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
838 >                ps.add(e.nextElement());
839 >            return "AdjustablePolicy with permissions " + ps;
840 >        }
841      }
842  
843 +    /**
844 +     * Returns a policy containing all the permissions we ever need.
845 +     */
846 +    public static Policy permissivePolicy() {
847 +        return new AdjustablePolicy
848 +            // Permissions j.u.c. needs directly
849 +            (new RuntimePermission("modifyThread"),
850 +             new RuntimePermission("getClassLoader"),
851 +             new RuntimePermission("setContextClassLoader"),
852 +             // Permissions needed to change permissions!
853 +             new SecurityPermission("getPolicy"),
854 +             new SecurityPermission("setPolicy"),
855 +             new RuntimePermission("setSecurityManager"),
856 +             // Permissions needed by the junit test harness
857 +             new RuntimePermission("accessDeclaredMembers"),
858 +             new PropertyPermission("*", "read"),
859 +             new java.io.FilePermission("<<ALL FILES>>", "read"));
860 +    }
861 +
862 +    /**
863 +     * Sleeps until the given time has elapsed.
864 +     * Throws AssertionFailedError if interrupted.
865 +     */
866 +    void sleep(long millis) {
867 +        try {
868 +            delay(millis);
869 +        } catch (InterruptedException ie) {
870 +            AssertionFailedError afe =
871 +                new AssertionFailedError("Unexpected InterruptedException");
872 +            afe.initCause(ie);
873 +            throw afe;
874 +        }
875 +    }
876 +
877 +    /**
878 +     * Spin-waits up to the specified number of milliseconds for the given
879 +     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
880 +     */
881 +    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
882 +        long startTime = System.nanoTime();
883 +        for (;;) {
884 +            Thread.State s = thread.getState();
885 +            if (s == Thread.State.BLOCKED ||
886 +                s == Thread.State.WAITING ||
887 +                s == Thread.State.TIMED_WAITING)
888 +                return;
889 +            else if (s == Thread.State.TERMINATED)
890 +                fail("Unexpected thread termination");
891 +            else if (millisElapsedSince(startTime) > timeoutMillis) {
892 +                threadAssertTrue(thread.isAlive());
893 +                return;
894 +            }
895 +            Thread.yield();
896 +        }
897 +    }
898 +
899 +    /**
900 +     * Waits up to LONG_DELAY_MS for the given thread to enter a wait
901 +     * state: BLOCKED, WAITING, or TIMED_WAITING.
902 +     */
903 +    void waitForThreadToEnterWaitState(Thread thread) {
904 +        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
905 +    }
906 +
907 +    /**
908 +     * Returns the number of milliseconds since time given by
909 +     * startNanoTime, which must have been previously returned from a
910 +     * call to {@link System.nanoTime()}.
911 +     */
912 +    static long millisElapsedSince(long startNanoTime) {
913 +        return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
914 +    }
915 +
916 + //     void assertTerminatesPromptly(long timeoutMillis, Runnable r) {
917 + //         long startTime = System.nanoTime();
918 + //         try {
919 + //             r.run();
920 + //         } catch (Throwable fail) { threadUnexpectedException(fail); }
921 + //         if (millisElapsedSince(startTime) > timeoutMillis/2)
922 + //             throw new AssertionFailedError("did not return promptly");
923 + //     }
924 +
925 + //     void assertTerminatesPromptly(Runnable r) {
926 + //         assertTerminatesPromptly(LONG_DELAY_MS/2, r);
927 + //     }
928 +
929 +    /**
930 +     * Checks that timed f.get() returns the expected value, and does not
931 +     * wait for the timeout to elapse before returning.
932 +     */
933 +    <T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) {
934 +        long startTime = System.nanoTime();
935 +        try {
936 +            assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
937 +        } catch (Throwable fail) { threadUnexpectedException(fail); }
938 +        if (millisElapsedSince(startTime) > timeoutMillis/2)
939 +            throw new AssertionFailedError("timed get did not return promptly");
940 +    }
941 +
942 +    <T> void checkTimedGet(Future<T> f, T expectedValue) {
943 +        checkTimedGet(f, expectedValue, LONG_DELAY_MS);
944 +    }
945 +
946 +    /**
947 +     * Returns a new started daemon Thread running the given runnable.
948 +     */
949 +    Thread newStartedThread(Runnable runnable) {
950 +        Thread t = new Thread(runnable);
951 +        t.setDaemon(true);
952 +        t.start();
953 +        return t;
954 +    }
955 +
956 +    /**
957 +     * Waits for the specified time (in milliseconds) for the thread
958 +     * to terminate (using {@link Thread#join(long)}), else interrupts
959 +     * the thread (in the hope that it may terminate later) and fails.
960 +     */
961 +    void awaitTermination(Thread t, long timeoutMillis) {
962 +        try {
963 +            t.join(timeoutMillis);
964 +        } catch (InterruptedException ie) {
965 +            threadUnexpectedException(ie);
966 +        } finally {
967 +            if (t.getState() != Thread.State.TERMINATED) {
968 +                t.interrupt();
969 +                fail("Test timed out");
970 +            }
971 +        }
972 +    }
973 +
974 +    /**
975 +     * Waits for LONG_DELAY_MS milliseconds for the thread to
976 +     * terminate (using {@link Thread#join(long)}), else interrupts
977 +     * the thread (in the hope that it may terminate later) and fails.
978 +     */
979 +    void awaitTermination(Thread t) {
980 +        awaitTermination(t, LONG_DELAY_MS);
981 +    }
982  
983      // Some convenient Runnable classes
984  
985 <    abstract class CheckedRunnable implements Runnable {
986 <        abstract void realRun() throws Throwable;
985 >    public abstract class CheckedRunnable implements Runnable {
986 >        protected abstract void realRun() throws Throwable;
987  
988          public final void run() {
989              try {
# Line 406 | Line 994 | public class JSR166TestCase extends Test
994          }
995      }
996  
997 <    abstract class CheckedInterruptedRunnable implements Runnable {
998 <        abstract void realRun() throws Throwable;
997 >    public abstract class RunnableShouldThrow implements Runnable {
998 >        protected abstract void realRun() throws Throwable;
999 >
1000 >        final Class<?> exceptionClass;
1001 >
1002 >        <T extends Throwable> RunnableShouldThrow(Class<T> exceptionClass) {
1003 >            this.exceptionClass = exceptionClass;
1004 >        }
1005 >
1006 >        public final void run() {
1007 >            try {
1008 >                realRun();
1009 >                threadShouldThrow(exceptionClass.getSimpleName());
1010 >            } catch (Throwable t) {
1011 >                if (! exceptionClass.isInstance(t))
1012 >                    threadUnexpectedException(t);
1013 >            }
1014 >        }
1015 >    }
1016 >
1017 >    public abstract class ThreadShouldThrow extends Thread {
1018 >        protected abstract void realRun() throws Throwable;
1019 >
1020 >        final Class<?> exceptionClass;
1021 >
1022 >        <T extends Throwable> ThreadShouldThrow(Class<T> exceptionClass) {
1023 >            this.exceptionClass = exceptionClass;
1024 >        }
1025  
1026          public final void run() {
1027              try {
1028                  realRun();
1029 <                threadShouldThrow();
1029 >                threadShouldThrow(exceptionClass.getSimpleName());
1030 >            } catch (Throwable t) {
1031 >                if (! exceptionClass.isInstance(t))
1032 >                    threadUnexpectedException(t);
1033 >            }
1034 >        }
1035 >    }
1036 >
1037 >    public abstract class CheckedInterruptedRunnable implements Runnable {
1038 >        protected abstract void realRun() throws Throwable;
1039 >
1040 >        public final void run() {
1041 >            try {
1042 >                realRun();
1043 >                threadShouldThrow("InterruptedException");
1044              } catch (InterruptedException success) {
1045 +                threadAssertFalse(Thread.interrupted());
1046              } catch (Throwable t) {
1047                  threadUnexpectedException(t);
1048              }
1049          }
1050      }
1051  
1052 <    abstract class CheckedCallable<T> implements Callable<T> {
1053 <        abstract T realCall() throws Throwable;
1052 >    public abstract class CheckedCallable<T> implements Callable<T> {
1053 >        protected abstract T realCall() throws Throwable;
1054  
1055          public final T call() {
1056              try {
# Line 433 | Line 1062 | public class JSR166TestCase extends Test
1062          }
1063      }
1064  
1065 <    static class NoOpRunnable implements Runnable {
1065 >    public abstract class CheckedInterruptedCallable<T>
1066 >        implements Callable<T> {
1067 >        protected abstract T realCall() throws Throwable;
1068 >
1069 >        public final T call() {
1070 >            try {
1071 >                T result = realCall();
1072 >                threadShouldThrow("InterruptedException");
1073 >                return result;
1074 >            } catch (InterruptedException success) {
1075 >                threadAssertFalse(Thread.interrupted());
1076 >            } catch (Throwable t) {
1077 >                threadUnexpectedException(t);
1078 >            }
1079 >            return null;
1080 >        }
1081 >    }
1082 >
1083 >    public static class NoOpRunnable implements Runnable {
1084          public void run() {}
1085      }
1086  
1087 <    static class NoOpCallable implements Callable {
1087 >    public static class NoOpCallable implements Callable {
1088          public Object call() { return Boolean.TRUE; }
1089      }
1090  
1091 <    static final String TEST_STRING = "a test string";
1091 >    public static final String TEST_STRING = "a test string";
1092  
1093 <    static class StringTask implements Callable<String> {
1093 >    public static class StringTask implements Callable<String> {
1094          public String call() { return TEST_STRING; }
1095      }
1096  
1097 <    static class NPETask implements Callable<String> {
1097 >    public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
1098 >        return new CheckedCallable<String>() {
1099 >            protected String realCall() {
1100 >                try {
1101 >                    latch.await();
1102 >                } catch (InterruptedException quittingTime) {}
1103 >                return TEST_STRING;
1104 >            }};
1105 >    }
1106 >
1107 >    public Runnable awaiter(final CountDownLatch latch) {
1108 >        return new CheckedRunnable() {
1109 >            public void realRun() throws InterruptedException {
1110 >                await(latch);
1111 >            }};
1112 >    }
1113 >
1114 >    public void await(CountDownLatch latch) {
1115 >        try {
1116 >            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1117 >        } catch (Throwable t) {
1118 >            threadUnexpectedException(t);
1119 >        }
1120 >    }
1121 >
1122 >    public void await(Semaphore semaphore) {
1123 >        try {
1124 >            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1125 >        } catch (Throwable t) {
1126 >            threadUnexpectedException(t);
1127 >        }
1128 >    }
1129 >
1130 > //     /**
1131 > //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1132 > //      */
1133 > //     public void await(AtomicBoolean flag) {
1134 > //         await(flag, LONG_DELAY_MS);
1135 > //     }
1136 >
1137 > //     /**
1138 > //      * Spin-waits up to the specified timeout until flag becomes true.
1139 > //      */
1140 > //     public void await(AtomicBoolean flag, long timeoutMillis) {
1141 > //         long startTime = System.nanoTime();
1142 > //         while (!flag.get()) {
1143 > //             if (millisElapsedSince(startTime) > timeoutMillis)
1144 > //                 throw new AssertionFailedError("timed out");
1145 > //             Thread.yield();
1146 > //         }
1147 > //     }
1148 >
1149 >    public static class NPETask implements Callable<String> {
1150          public String call() { throw new NullPointerException(); }
1151      }
1152  
1153 <    static class CallableOne implements Callable<Integer> {
1153 >    public static class CallableOne implements Callable<Integer> {
1154          public Integer call() { return one; }
1155      }
1156  
1157 <    class ShortRunnable extends CheckedRunnable {
1158 <        void realRun() throws Throwable {
1159 <            Thread.sleep(SHORT_DELAY_MS);
1157 >    public class ShortRunnable extends CheckedRunnable {
1158 >        protected void realRun() throws Throwable {
1159 >            delay(SHORT_DELAY_MS);
1160          }
1161      }
1162  
1163 <    class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1164 <        void realRun() throws InterruptedException {
1165 <            Thread.sleep(SHORT_DELAY_MS);
1163 >    public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1164 >        protected void realRun() throws InterruptedException {
1165 >            delay(SHORT_DELAY_MS);
1166          }
1167      }
1168  
1169 <    class SmallRunnable extends CheckedRunnable {
1170 <        void realRun() throws Throwable {
1171 <            Thread.sleep(SMALL_DELAY_MS);
1169 >    public class SmallRunnable extends CheckedRunnable {
1170 >        protected void realRun() throws Throwable {
1171 >            delay(SMALL_DELAY_MS);
1172          }
1173      }
1174  
1175 <    class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1176 <        void realRun() {
1175 >    public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1176 >        protected void realRun() {
1177              try {
1178 <                Thread.sleep(SMALL_DELAY_MS);
1179 <            }
481 <            catch (InterruptedException ok) {
482 <            }
1178 >                delay(SMALL_DELAY_MS);
1179 >            } catch (InterruptedException ok) {}
1180          }
1181      }
1182  
1183 <    class SmallCallable extends CheckedCallable {
1184 <        Object realCall() throws Throwable {
1185 <            Thread.sleep(SMALL_DELAY_MS);
1183 >    public class SmallCallable extends CheckedCallable {
1184 >        protected Object realCall() throws InterruptedException {
1185 >            delay(SMALL_DELAY_MS);
1186              return Boolean.TRUE;
1187          }
1188      }
1189  
1190 <    class SmallInterruptedRunnable extends CheckedInterruptedRunnable {
1191 <        void realRun() throws InterruptedException {
1192 <            Thread.sleep(SMALL_DELAY_MS);
1190 >    public class MediumRunnable extends CheckedRunnable {
1191 >        protected void realRun() throws Throwable {
1192 >            delay(MEDIUM_DELAY_MS);
1193          }
1194      }
1195  
1196 <    class MediumRunnable extends CheckedRunnable {
1197 <        void realRun() throws Throwable {
1198 <            Thread.sleep(MEDIUM_DELAY_MS);
1196 >    public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1197 >        protected void realRun() throws InterruptedException {
1198 >            delay(MEDIUM_DELAY_MS);
1199          }
1200      }
1201  
1202 <    class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1203 <        void realRun() throws InterruptedException {
1204 <            Thread.sleep(MEDIUM_DELAY_MS);
1205 <        }
1202 >    public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1203 >        return new CheckedRunnable() {
1204 >            protected void realRun() {
1205 >                try {
1206 >                    delay(timeoutMillis);
1207 >                } catch (InterruptedException ok) {}
1208 >            }};
1209      }
1210  
1211 <    class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1212 <        void realRun() {
1211 >    public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1212 >        protected void realRun() {
1213              try {
1214 <                Thread.sleep(MEDIUM_DELAY_MS);
1215 <            }
516 <            catch (InterruptedException ok) {
517 <            }
1214 >                delay(MEDIUM_DELAY_MS);
1215 >            } catch (InterruptedException ok) {}
1216          }
1217      }
1218  
1219 <    class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1220 <        void realRun() {
1219 >    public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1220 >        protected void realRun() {
1221              try {
1222 <                Thread.sleep(LONG_DELAY_MS);
1223 <            }
526 <            catch (InterruptedException ok) {
527 <            }
1222 >                delay(LONG_DELAY_MS);
1223 >            } catch (InterruptedException ok) {}
1224          }
1225      }
1226  
1227      /**
1228       * For use as ThreadFactory in constructors
1229       */
1230 <    static class SimpleThreadFactory implements ThreadFactory {
1230 >    public static class SimpleThreadFactory implements ThreadFactory {
1231          public Thread newThread(Runnable r) {
1232              return new Thread(r);
1233          }
1234      }
1235  
1236 <    static class TrackedShortRunnable implements Runnable {
1237 <        volatile boolean done = false;
1236 >    public interface TrackedRunnable extends Runnable {
1237 >        boolean isDone();
1238 >    }
1239 >
1240 >    public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
1241 >        return new TrackedRunnable() {
1242 >                private volatile boolean done = false;
1243 >                public boolean isDone() { return done; }
1244 >                public void run() {
1245 >                    try {
1246 >                        delay(timeoutMillis);
1247 >                        done = true;
1248 >                    } catch (InterruptedException ok) {}
1249 >                }
1250 >            };
1251 >    }
1252 >
1253 >    public static class TrackedShortRunnable implements Runnable {
1254 >        public volatile boolean done = false;
1255          public void run() {
1256              try {
1257 <                Thread.sleep(SMALL_DELAY_MS);
1257 >                delay(SHORT_DELAY_MS);
1258                  done = true;
1259 <            } catch (Exception e) {
547 <            }
1259 >            } catch (InterruptedException ok) {}
1260          }
1261      }
1262  
1263 <    static class TrackedMediumRunnable implements Runnable {
1264 <        volatile boolean done = false;
1263 >    public static class TrackedSmallRunnable implements Runnable {
1264 >        public volatile boolean done = false;
1265          public void run() {
1266              try {
1267 <                Thread.sleep(MEDIUM_DELAY_MS);
1267 >                delay(SMALL_DELAY_MS);
1268                  done = true;
1269 <            } catch (Exception e) {
558 <            }
1269 >            } catch (InterruptedException ok) {}
1270          }
1271      }
1272  
1273 <    static class TrackedLongRunnable implements Runnable {
1274 <        volatile boolean done = false;
1273 >    public static class TrackedMediumRunnable implements Runnable {
1274 >        public volatile boolean done = false;
1275          public void run() {
1276              try {
1277 <                Thread.sleep(LONG_DELAY_MS);
1277 >                delay(MEDIUM_DELAY_MS);
1278                  done = true;
1279 <            } catch (Exception e) {
1280 <            }
1279 >            } catch (InterruptedException ok) {}
1280 >        }
1281 >    }
1282 >
1283 >    public static class TrackedLongRunnable implements Runnable {
1284 >        public volatile boolean done = false;
1285 >        public void run() {
1286 >            try {
1287 >                delay(LONG_DELAY_MS);
1288 >                done = true;
1289 >            } catch (InterruptedException ok) {}
1290          }
1291      }
1292  
1293 <    static class TrackedNoOpRunnable implements Runnable {
1294 <        volatile boolean done = false;
1293 >    public static class TrackedNoOpRunnable implements Runnable {
1294 >        public volatile boolean done = false;
1295          public void run() {
1296              done = true;
1297          }
1298      }
1299  
1300 <    static class TrackedCallable implements Callable {
1301 <        volatile boolean done = false;
1300 >    public static class TrackedCallable implements Callable {
1301 >        public volatile boolean done = false;
1302          public Object call() {
1303              try {
1304 <                Thread.sleep(SMALL_DELAY_MS);
1304 >                delay(SMALL_DELAY_MS);
1305                  done = true;
1306 <            } catch (Exception e) {
587 <            }
1306 >            } catch (InterruptedException ok) {}
1307              return Boolean.TRUE;
1308          }
1309      }
1310  
1311 +    /**
1312 +     * Analog of CheckedRunnable for RecursiveAction
1313 +     */
1314 +    public abstract class CheckedRecursiveAction extends RecursiveAction {
1315 +        protected abstract void realCompute() throws Throwable;
1316 +
1317 +        @Override protected final void compute() {
1318 +            try {
1319 +                realCompute();
1320 +            } catch (Throwable t) {
1321 +                threadUnexpectedException(t);
1322 +            }
1323 +        }
1324 +    }
1325 +
1326 +    /**
1327 +     * Analog of CheckedCallable for RecursiveTask
1328 +     */
1329 +    public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1330 +        protected abstract T realCompute() throws Throwable;
1331 +
1332 +        @Override protected final T compute() {
1333 +            try {
1334 +                return realCompute();
1335 +            } catch (Throwable t) {
1336 +                threadUnexpectedException(t);
1337 +                return null;
1338 +            }
1339 +        }
1340 +    }
1341  
1342      /**
1343       * For use as RejectedExecutionHandler in constructors
1344       */
1345 <    static class NoOpREHandler implements RejectedExecutionHandler {
1345 >    public static class NoOpREHandler implements RejectedExecutionHandler {
1346          public void rejectedExecution(Runnable r,
1347                                        ThreadPoolExecutor executor) {}
1348      }
1349  
1350 +    /**
1351 +     * A CyclicBarrier that uses timed await and fails with
1352 +     * AssertionFailedErrors instead of throwing checked exceptions.
1353 +     */
1354 +    public class CheckedBarrier extends CyclicBarrier {
1355 +        public CheckedBarrier(int parties) { super(parties); }
1356 +
1357 +        public int await() {
1358 +            try {
1359 +                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1360 +            } catch (TimeoutException e) {
1361 +                throw new AssertionFailedError("timed out");
1362 +            } catch (Exception e) {
1363 +                AssertionFailedError afe =
1364 +                    new AssertionFailedError("Unexpected exception: " + e);
1365 +                afe.initCause(e);
1366 +                throw afe;
1367 +            }
1368 +        }
1369 +    }
1370 +
1371 +    void checkEmpty(BlockingQueue q) {
1372 +        try {
1373 +            assertTrue(q.isEmpty());
1374 +            assertEquals(0, q.size());
1375 +            assertNull(q.peek());
1376 +            assertNull(q.poll());
1377 +            assertNull(q.poll(0, MILLISECONDS));
1378 +            assertEquals(q.toString(), "[]");
1379 +            assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1380 +            assertFalse(q.iterator().hasNext());
1381 +            try {
1382 +                q.element();
1383 +                shouldThrow();
1384 +            } catch (NoSuchElementException success) {}
1385 +            try {
1386 +                q.iterator().next();
1387 +                shouldThrow();
1388 +            } catch (NoSuchElementException success) {}
1389 +            try {
1390 +                q.remove();
1391 +                shouldThrow();
1392 +            } catch (NoSuchElementException success) {}
1393 +        } catch (InterruptedException ie) {
1394 +            threadUnexpectedException(ie);
1395 +        }
1396 +    }
1397 +
1398 +    void assertSerialEquals(Object x, Object y) {
1399 +        assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1400 +    }
1401 +
1402 +    void assertNotSerialEquals(Object x, Object y) {
1403 +        assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1404 +    }
1405 +
1406 +    byte[] serialBytes(Object o) {
1407 +        try {
1408 +            ByteArrayOutputStream bos = new ByteArrayOutputStream();
1409 +            ObjectOutputStream oos = new ObjectOutputStream(bos);
1410 +            oos.writeObject(o);
1411 +            oos.flush();
1412 +            oos.close();
1413 +            return bos.toByteArray();
1414 +        } catch (Throwable t) {
1415 +            threadUnexpectedException(t);
1416 +            return new byte[0];
1417 +        }
1418 +    }
1419 +
1420 +    @SuppressWarnings("unchecked")
1421 +    <T> T serialClone(T o) {
1422 +        try {
1423 +            ObjectInputStream ois = new ObjectInputStream
1424 +                (new ByteArrayInputStream(serialBytes(o)));
1425 +            T clone = (T) ois.readObject();
1426 +            assertSame(o.getClass(), clone.getClass());
1427 +            return clone;
1428 +        } catch (Throwable t) {
1429 +            threadUnexpectedException(t);
1430 +            return null;
1431 +        }
1432 +    }
1433 +
1434 +    public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1435 +                             Runnable... throwingActions) {
1436 +        for (Runnable throwingAction : throwingActions) {
1437 +            boolean threw = false;
1438 +            try { throwingAction.run(); }
1439 +            catch (Throwable t) {
1440 +                threw = true;
1441 +                if (!expectedExceptionClass.isInstance(t)) {
1442 +                    AssertionFailedError afe =
1443 +                        new AssertionFailedError
1444 +                        ("Expected " + expectedExceptionClass.getName() +
1445 +                         ", got " + t.getClass().getName());
1446 +                    afe.initCause(t);
1447 +                    threadUnexpectedException(afe);
1448 +                }
1449 +            }
1450 +            if (!threw)
1451 +                shouldThrow(expectedExceptionClass.getName());
1452 +        }
1453 +    }
1454   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines