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.29 by dl, Sat Oct 1 17:05:38 2005 UTC vs.
Revision 1.133 by jsr166, Sun May 24 01:53:55 2015 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines