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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines