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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines