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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines