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.49 by jsr166, Tue Jan 5 02:08:37 2010 UTC vs.
Revision 1.82 by jsr166, Tue May 24 23:34:03 2011 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.Arrays;
15 > import java.util.Date;
16 > import java.util.NoSuchElementException;
17 > import java.util.PropertyPermission;
18   import java.util.concurrent.*;
19 + import java.util.concurrent.atomic.AtomicBoolean;
20 + import java.util.concurrent.atomic.AtomicReference;
21   import static java.util.concurrent.TimeUnit.MILLISECONDS;
22 < import java.io.*;
23 < import java.security.*;
22 > import static java.util.concurrent.TimeUnit.NANOSECONDS;
23 > import java.security.CodeSource;
24 > import java.security.Permission;
25 > import java.security.PermissionCollection;
26 > import java.security.Permissions;
27 > import java.security.Policy;
28 > import java.security.ProtectionDomain;
29 > import java.security.SecurityPermission;
30  
31   /**
32   * Base class for JSR166 Junit TCK tests.  Defines some constants,
# Line 26 | Line 41 | import java.security.*;
41   * <li> All assertions in code running in generated threads must use
42   * the forms {@link #threadFail}, {@link #threadAssertTrue}, {@link
43   * #threadAssertEquals}, or {@link #threadAssertNull}, (not
44 < * <tt>fail</tt>, <tt>assertTrue</tt>, etc.) It is OK (but not
44 > * {@code fail}, {@code assertTrue}, etc.) It is OK (but not
45   * particularly recommended) for other code to use these forms too.
46   * Only the most typically used JUnit assertion methods are defined
47   * this way, but enough to live with.</li>
48   *
49   * <li> If you override {@link #setUp} or {@link #tearDown}, make sure
50 < * to invoke <tt>super.setUp</tt> and <tt>super.tearDown</tt> within
50 > * to invoke {@code super.setUp} and {@code super.tearDown} within
51   * them. These methods are used to clear and check for thread
52   * assertion failures.</li>
53   *
54 < * <li>All delays and timeouts must use one of the constants <tt>
55 < * SHORT_DELAY_MS</tt>, <tt> SMALL_DELAY_MS</tt>, <tt> MEDIUM_DELAY_MS</tt>,
56 < * <tt> LONG_DELAY_MS</tt>. The idea here is that a SHORT is always
54 > * <li>All delays and timeouts must use one of the constants {@code
55 > * SHORT_DELAY_MS}, {@code SMALL_DELAY_MS}, {@code MEDIUM_DELAY_MS},
56 > * {@code LONG_DELAY_MS}. The idea here is that a SHORT is always
57   * discriminable from zero time, and always allows enough time for the
58   * small amounts of computation (creating a thread, calling a few
59   * methods, etc) needed to reach a timeout point. Similarly, a SMALL
# Line 48 | Line 63 | import java.security.*;
63   * in one spot to rerun tests on slower platforms.</li>
64   *
65   * <li> All threads generated must be joined inside each test case
66 < * method (or <tt>fail</tt> to do so) before returning from the
67 < * method. The <tt> joinPool</tt> method can be used to do this when
66 > * method (or {@code fail} to do so) before returning from the
67 > * method. The {@code joinPool} method can be used to do this when
68   * using Executors.</li>
69   *
70   * </ol>
# Line 81 | Line 96 | import java.security.*;
96   * any particular package to simplify things for people integrating
97   * them in TCK test suites.</li>
98   *
99 < * <li> As a convenience, the <tt>main</tt> of this class (JSR166TestCase)
99 > * <li> As a convenience, the {@code main} of this class (JSR166TestCase)
100   * runs all JSR166 unit tests.</li>
101   *
102   * </ul>
# Line 90 | Line 105 | public class JSR166TestCase extends Test
105      private static final boolean useSecurityManager =
106          Boolean.getBoolean("jsr166.useSecurityManager");
107  
108 +    protected static final boolean expensiveTests =
109 +        Boolean.getBoolean("jsr166.expensiveTests");
110 +
111 +    /**
112 +     * If true, report on stdout all "slow" tests, that is, ones that
113 +     * take more than profileThreshold milliseconds to execute.
114 +     */
115 +    private static final boolean profileTests =
116 +        Boolean.getBoolean("jsr166.profileTests");
117 +
118 +    /**
119 +     * The number of milliseconds that tests are permitted for
120 +     * execution without being reported, when profileTests is set.
121 +     */
122 +    private static final long profileThreshold =
123 +        Long.getLong("jsr166.profileThreshold", 100);
124 +
125 +    protected void runTest() throws Throwable {
126 +        if (profileTests)
127 +            runTestProfiled();
128 +        else
129 +            super.runTest();
130 +    }
131 +
132 +    protected void runTestProfiled() throws Throwable {
133 +        long t0 = System.nanoTime();
134 +        try {
135 +            super.runTest();
136 +        } finally {
137 +            long elapsedMillis =
138 +                (System.nanoTime() - t0) / (1000L * 1000L);
139 +            if (elapsedMillis >= profileThreshold)
140 +                System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
141 +        }
142 +    }
143 +
144      /**
145       * Runs all JSR166 unit tests using junit.textui.TestRunner
146       */
# Line 99 | Line 150 | public class JSR166TestCase extends Test
150              Policy.setPolicy(permissivePolicy());
151              System.setSecurityManager(new SecurityManager());
152          }
153 <        int iters = 1;
154 <        if (args.length > 0)
104 <            iters = Integer.parseInt(args[0]);
153 >        int iters = (args.length == 0) ? 1 : Integer.parseInt(args[0]);
154 >
155          Test s = suite();
156          for (int i = 0; i < iters; ++i) {
157              junit.textui.TestRunner.run(s);
# Line 111 | Line 161 | public class JSR166TestCase extends Test
161          System.exit(0);
162      }
163  
164 +    public static TestSuite newTestSuite(Object... suiteOrClasses) {
165 +        TestSuite suite = new TestSuite();
166 +        for (Object suiteOrClass : suiteOrClasses) {
167 +            if (suiteOrClass instanceof TestSuite)
168 +                suite.addTest((TestSuite) suiteOrClass);
169 +            else if (suiteOrClass instanceof Class)
170 +                suite.addTest(new TestSuite((Class<?>) suiteOrClass));
171 +            else
172 +                throw new ClassCastException("not a test suite or class");
173 +        }
174 +        return suite;
175 +    }
176 +
177      /**
178 <     * Collects all JSR166 unit tests as one suite
178 >     * Collects all JSR166 unit tests as one suite.
179       */
180      public static Test suite() {
181 <        TestSuite suite = new TestSuite("JSR166 Unit Tests");
182 <
183 <        suite.addTest(new TestSuite(ForkJoinPoolTest.class));
184 <        suite.addTest(new TestSuite(ForkJoinTaskTest.class));
185 <        suite.addTest(new TestSuite(RecursiveActionTest.class));
186 <        suite.addTest(new TestSuite(RecursiveTaskTest.class));
187 <        suite.addTest(new TestSuite(LinkedTransferQueueTest.class));
188 <        suite.addTest(new TestSuite(PhaserTest.class));
189 <        suite.addTest(new TestSuite(ThreadLocalRandomTest.class));
190 <        suite.addTest(new TestSuite(AbstractExecutorServiceTest.class));
191 <        suite.addTest(new TestSuite(AbstractQueueTest.class));
192 <        suite.addTest(new TestSuite(AbstractQueuedSynchronizerTest.class));
193 <        suite.addTest(new TestSuite(AbstractQueuedLongSynchronizerTest.class));
194 <        suite.addTest(new TestSuite(ArrayBlockingQueueTest.class));
195 <        suite.addTest(new TestSuite(ArrayDequeTest.class));
196 <        suite.addTest(new TestSuite(AtomicBooleanTest.class));
197 <        suite.addTest(new TestSuite(AtomicIntegerArrayTest.class));
198 <        suite.addTest(new TestSuite(AtomicIntegerFieldUpdaterTest.class));
199 <        suite.addTest(new TestSuite(AtomicIntegerTest.class));
200 <        suite.addTest(new TestSuite(AtomicLongArrayTest.class));
201 <        suite.addTest(new TestSuite(AtomicLongFieldUpdaterTest.class));
202 <        suite.addTest(new TestSuite(AtomicLongTest.class));
203 <        suite.addTest(new TestSuite(AtomicMarkableReferenceTest.class));
204 <        suite.addTest(new TestSuite(AtomicReferenceArrayTest.class));
205 <        suite.addTest(new TestSuite(AtomicReferenceFieldUpdaterTest.class));
206 <        suite.addTest(new TestSuite(AtomicReferenceTest.class));
207 <        suite.addTest(new TestSuite(AtomicStampedReferenceTest.class));
208 <        suite.addTest(new TestSuite(ConcurrentHashMapTest.class));
209 <        suite.addTest(new TestSuite(ConcurrentLinkedQueueTest.class));
210 <        suite.addTest(new TestSuite(ConcurrentSkipListMapTest.class));
211 <        suite.addTest(new TestSuite(ConcurrentSkipListSubMapTest.class));
212 <        suite.addTest(new TestSuite(ConcurrentSkipListSetTest.class));
213 <        suite.addTest(new TestSuite(ConcurrentSkipListSubSetTest.class));
214 <        suite.addTest(new TestSuite(CopyOnWriteArrayListTest.class));
215 <        suite.addTest(new TestSuite(CopyOnWriteArraySetTest.class));
216 <        suite.addTest(new TestSuite(CountDownLatchTest.class));
217 <        suite.addTest(new TestSuite(CyclicBarrierTest.class));
218 <        suite.addTest(new TestSuite(DelayQueueTest.class));
219 <        suite.addTest(new TestSuite(EntryTest.class));
220 <        suite.addTest(new TestSuite(ExchangerTest.class));
221 <        suite.addTest(new TestSuite(ExecutorsTest.class));
222 <        suite.addTest(new TestSuite(ExecutorCompletionServiceTest.class));
223 <        suite.addTest(new TestSuite(FutureTaskTest.class));
224 <        suite.addTest(new TestSuite(LinkedBlockingDequeTest.class));
225 <        suite.addTest(new TestSuite(LinkedBlockingQueueTest.class));
226 <        suite.addTest(new TestSuite(LinkedListTest.class));
227 <        suite.addTest(new TestSuite(LockSupportTest.class));
228 <        suite.addTest(new TestSuite(PriorityBlockingQueueTest.class));
229 <        suite.addTest(new TestSuite(PriorityQueueTest.class));
230 <        suite.addTest(new TestSuite(ReentrantLockTest.class));
231 <        suite.addTest(new TestSuite(ReentrantReadWriteLockTest.class));
232 <        suite.addTest(new TestSuite(ScheduledExecutorTest.class));
233 <        suite.addTest(new TestSuite(ScheduledExecutorSubclassTest.class));
234 <        suite.addTest(new TestSuite(SemaphoreTest.class));
235 <        suite.addTest(new TestSuite(SynchronousQueueTest.class));
236 <        suite.addTest(new TestSuite(SystemTest.class));
237 <        suite.addTest(new TestSuite(ThreadLocalTest.class));
238 <        suite.addTest(new TestSuite(ThreadPoolExecutorTest.class));
239 <        suite.addTest(new TestSuite(ThreadPoolExecutorSubclassTest.class));
240 <        suite.addTest(new TestSuite(ThreadTest.class));
241 <        suite.addTest(new TestSuite(TimeUnitTest.class));
242 <        suite.addTest(new TestSuite(TreeMapTest.class));
243 <        suite.addTest(new TestSuite(TreeSetTest.class));
244 <        suite.addTest(new TestSuite(TreeSubMapTest.class));
245 <        suite.addTest(new TestSuite(TreeSubSetTest.class));
183 <
184 <        return suite;
181 >        return newTestSuite(
182 >            ForkJoinPoolTest.suite(),
183 >            ForkJoinTaskTest.suite(),
184 >            RecursiveActionTest.suite(),
185 >            RecursiveTaskTest.suite(),
186 >            LinkedTransferQueueTest.suite(),
187 >            PhaserTest.suite(),
188 >            ThreadLocalRandomTest.suite(),
189 >            AbstractExecutorServiceTest.suite(),
190 >            AbstractQueueTest.suite(),
191 >            AbstractQueuedSynchronizerTest.suite(),
192 >            AbstractQueuedLongSynchronizerTest.suite(),
193 >            ArrayBlockingQueueTest.suite(),
194 >            ArrayDequeTest.suite(),
195 >            AtomicBooleanTest.suite(),
196 >            AtomicIntegerArrayTest.suite(),
197 >            AtomicIntegerFieldUpdaterTest.suite(),
198 >            AtomicIntegerTest.suite(),
199 >            AtomicLongArrayTest.suite(),
200 >            AtomicLongFieldUpdaterTest.suite(),
201 >            AtomicLongTest.suite(),
202 >            AtomicMarkableReferenceTest.suite(),
203 >            AtomicReferenceArrayTest.suite(),
204 >            AtomicReferenceFieldUpdaterTest.suite(),
205 >            AtomicReferenceTest.suite(),
206 >            AtomicStampedReferenceTest.suite(),
207 >            ConcurrentHashMapTest.suite(),
208 >            ConcurrentLinkedDequeTest.suite(),
209 >            ConcurrentLinkedQueueTest.suite(),
210 >            ConcurrentSkipListMapTest.suite(),
211 >            ConcurrentSkipListSubMapTest.suite(),
212 >            ConcurrentSkipListSetTest.suite(),
213 >            ConcurrentSkipListSubSetTest.suite(),
214 >            CopyOnWriteArrayListTest.suite(),
215 >            CopyOnWriteArraySetTest.suite(),
216 >            CountDownLatchTest.suite(),
217 >            CyclicBarrierTest.suite(),
218 >            DelayQueueTest.suite(),
219 >            EntryTest.suite(),
220 >            ExchangerTest.suite(),
221 >            ExecutorsTest.suite(),
222 >            ExecutorCompletionServiceTest.suite(),
223 >            FutureTaskTest.suite(),
224 >            LinkedBlockingDequeTest.suite(),
225 >            LinkedBlockingQueueTest.suite(),
226 >            LinkedListTest.suite(),
227 >            LockSupportTest.suite(),
228 >            PriorityBlockingQueueTest.suite(),
229 >            PriorityQueueTest.suite(),
230 >            ReentrantLockTest.suite(),
231 >            ReentrantReadWriteLockTest.suite(),
232 >            ScheduledExecutorTest.suite(),
233 >            ScheduledExecutorSubclassTest.suite(),
234 >            SemaphoreTest.suite(),
235 >            SynchronousQueueTest.suite(),
236 >            SystemTest.suite(),
237 >            ThreadLocalTest.suite(),
238 >            ThreadPoolExecutorTest.suite(),
239 >            ThreadPoolExecutorSubclassTest.suite(),
240 >            ThreadTest.suite(),
241 >            TimeUnitTest.suite(),
242 >            TreeMapTest.suite(),
243 >            TreeSetTest.suite(),
244 >            TreeSubMapTest.suite(),
245 >            TreeSubSetTest.suite());
246      }
247  
248  
# Line 205 | Line 266 | public class JSR166TestCase extends Test
266       */
267      protected void setDelays() {
268          SHORT_DELAY_MS = getShortDelay();
269 <        SMALL_DELAY_MS = SHORT_DELAY_MS * 5;
269 >        SMALL_DELAY_MS  = SHORT_DELAY_MS * 5;
270          MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
271 <        LONG_DELAY_MS = SHORT_DELAY_MS * 50;
271 >        LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
272 >    }
273 >
274 >    /**
275 >     * Returns a timeout in milliseconds to be used in tests that
276 >     * verify that operations block or time out.
277 >     */
278 >    long timeoutMillis() {
279 >        return SHORT_DELAY_MS / 4;
280      }
281  
282      /**
283 <     * Flag set true if any threadAssert methods fail
283 >     * Returns a new Date instance representing a time delayMillis
284 >     * milliseconds in the future.
285       */
286 <    volatile boolean threadFailed;
286 >    Date delayedDate(long delayMillis) {
287 >        return new Date(new Date().getTime() + delayMillis);
288 >    }
289  
290      /**
291 <     * Initializes test to indicate that no thread assertions have failed
291 >     * The first exception encountered if any threadAssertXXX method fails.
292       */
293 +    private final AtomicReference<Throwable> threadFailure
294 +        = new AtomicReference<Throwable>(null);
295 +
296 +    /**
297 +     * Records an exception so that it can be rethrown later in the test
298 +     * harness thread, triggering a test case failure.  Only the first
299 +     * failure is recorded; subsequent calls to this method from within
300 +     * the same test have no effect.
301 +     */
302 +    public void threadRecordFailure(Throwable t) {
303 +        threadFailure.compareAndSet(null, t);
304 +    }
305 +
306      public void setUp() {
307          setDelays();
223        threadFailed = false;
308      }
309  
310      /**
311 <     * Triggers test case failure if any thread assertions have failed
312 <     */
313 <    public void tearDown() {
314 <        assertFalse(threadFailed);
311 >     * Triggers test case failure if any thread assertions have failed,
312 >     * by rethrowing, in the test harness thread, any exception recorded
313 >     * earlier by threadRecordFailure.
314 >     */
315 >    public void tearDown() throws Exception {
316 >        Throwable t = threadFailure.getAndSet(null);
317 >        if (t != null) {
318 >            if (t instanceof Error)
319 >                throw (Error) t;
320 >            else if (t instanceof RuntimeException)
321 >                throw (RuntimeException) t;
322 >            else if (t instanceof Exception)
323 >                throw (Exception) t;
324 >            else {
325 >                AssertionFailedError afe =
326 >                    new AssertionFailedError(t.toString());
327 >                afe.initCause(t);
328 >                throw afe;
329 >            }
330 >        }
331      }
332  
333      /**
334 <     * Fail, also setting status to indicate current testcase should fail
334 >     * Just like fail(reason), but additionally recording (using
335 >     * threadRecordFailure) any AssertionFailedError thrown, so that
336 >     * the current testcase will fail.
337       */
338      public void threadFail(String reason) {
339 <        threadFailed = true;
340 <        fail(reason);
339 >        try {
340 >            fail(reason);
341 >        } catch (AssertionFailedError t) {
342 >            threadRecordFailure(t);
343 >            fail(reason);
344 >        }
345      }
346  
347      /**
348 <     * If expression not true, set status to indicate current testcase
349 <     * should fail
348 >     * Just like assertTrue(b), but additionally recording (using
349 >     * threadRecordFailure) any AssertionFailedError thrown, so that
350 >     * the current testcase will fail.
351       */
352      public void threadAssertTrue(boolean b) {
353 <        if (!b) {
247 <            threadFailed = true;
353 >        try {
354              assertTrue(b);
355 +        } catch (AssertionFailedError t) {
356 +            threadRecordFailure(t);
357 +            throw t;
358          }
359      }
360  
361      /**
362 <     * If expression not false, set status to indicate current testcase
363 <     * should fail
362 >     * Just like assertFalse(b), but additionally recording (using
363 >     * threadRecordFailure) any AssertionFailedError thrown, so that
364 >     * the current testcase will fail.
365       */
366      public void threadAssertFalse(boolean b) {
367 <        if (b) {
258 <            threadFailed = true;
367 >        try {
368              assertFalse(b);
369 +        } catch (AssertionFailedError t) {
370 +            threadRecordFailure(t);
371 +            throw t;
372          }
373      }
374  
375      /**
376 <     * If argument not null, set status to indicate current testcase
377 <     * should fail
376 >     * Just like assertNull(x), but additionally recording (using
377 >     * threadRecordFailure) any AssertionFailedError thrown, so that
378 >     * the current testcase will fail.
379       */
380      public void threadAssertNull(Object x) {
381 <        if (x != null) {
269 <            threadFailed = true;
381 >        try {
382              assertNull(x);
383 +        } catch (AssertionFailedError t) {
384 +            threadRecordFailure(t);
385 +            throw t;
386          }
387      }
388  
389      /**
390 <     * If arguments not equal, set status to indicate current testcase
391 <     * should fail
390 >     * Just like assertEquals(x, y), but additionally recording (using
391 >     * threadRecordFailure) any AssertionFailedError thrown, so that
392 >     * the current testcase will fail.
393       */
394      public void threadAssertEquals(long x, long y) {
395 <        if (x != y) {
280 <            threadFailed = true;
395 >        try {
396              assertEquals(x, y);
397 +        } catch (AssertionFailedError t) {
398 +            threadRecordFailure(t);
399 +            throw t;
400          }
401      }
402  
403      /**
404 <     * If arguments not equal, set status to indicate current testcase
405 <     * should fail
404 >     * Just like assertEquals(x, y), but additionally recording (using
405 >     * threadRecordFailure) any AssertionFailedError thrown, so that
406 >     * the current testcase will fail.
407       */
408      public void threadAssertEquals(Object x, Object y) {
409 <        if (x != y && (x == null || !x.equals(y))) {
291 <            threadFailed = true;
409 >        try {
410              assertEquals(x, y);
411 +        } catch (AssertionFailedError t) {
412 +            threadRecordFailure(t);
413 +            throw t;
414 +        } catch (Throwable t) {
415 +            threadUnexpectedException(t);
416 +        }
417 +    }
418 +
419 +    /**
420 +     * Just like assertSame(x, y), but additionally recording (using
421 +     * threadRecordFailure) any AssertionFailedError thrown, so that
422 +     * the current testcase will fail.
423 +     */
424 +    public void threadAssertSame(Object x, Object y) {
425 +        try {
426 +            assertSame(x, y);
427 +        } catch (AssertionFailedError t) {
428 +            threadRecordFailure(t);
429 +            throw t;
430          }
431      }
432  
433      /**
434 <     * threadFail with message "should throw exception"
434 >     * Calls threadFail with message "should throw exception".
435       */
436      public void threadShouldThrow() {
437 <        threadFailed = true;
301 <        fail("should throw exception");
437 >        threadFail("should throw exception");
438      }
439  
440      /**
441 <     * threadFail with message "should throw" + exceptionName
441 >     * Calls threadFail with message "should throw" + exceptionName.
442       */
443      public void threadShouldThrow(String exceptionName) {
444 <        threadFailed = true;
309 <        fail("should throw " + exceptionName);
444 >        threadFail("should throw " + exceptionName);
445      }
446  
447      /**
448 <     * threadFail with message "Unexpected exception"
448 >     * Records the given exception using {@link #threadRecordFailure},
449 >     * then rethrows the exception, wrapping it in an
450 >     * AssertionFailedError if necessary.
451       */
452 <    public void threadUnexpectedException() {
453 <        threadFailed = true;
454 <        fail("Unexpected exception");
452 >    public void threadUnexpectedException(Throwable t) {
453 >        threadRecordFailure(t);
454 >        t.printStackTrace();
455 >        if (t instanceof RuntimeException)
456 >            throw (RuntimeException) t;
457 >        else if (t instanceof Error)
458 >            throw (Error) t;
459 >        else {
460 >            AssertionFailedError afe =
461 >                new AssertionFailedError("unexpected exception: " + t);
462 >            afe.initCause(t);
463 >            throw afe;
464 >        }
465      }
466  
467      /**
468 <     * threadFail with message "Unexpected exception", with argument
468 >     * Delays, via Thread.sleep, for the given millisecond delay, but
469 >     * if the sleep is shorter than specified, may re-sleep or yield
470 >     * until time elapses.
471       */
472 <    public void threadUnexpectedException(Throwable ex) {
473 <        threadFailed = true;
474 <        ex.printStackTrace();
475 <        fail("Unexpected exception: " + ex);
472 >    static void delay(long millis) throws InterruptedException {
473 >        long startTime = System.nanoTime();
474 >        long ns = millis * 1000 * 1000;
475 >        for (;;) {
476 >            if (millis > 0L)
477 >                Thread.sleep(millis);
478 >            else // too short to sleep
479 >                Thread.yield();
480 >            long d = ns - (System.nanoTime() - startTime);
481 >            if (d > 0L)
482 >                millis = d / (1000 * 1000);
483 >            else
484 >                break;
485 >        }
486      }
487  
488      /**
489 <     * Wait out termination of a thread pool or fail doing so
489 >     * Waits out termination of a thread pool or fails doing so.
490       */
491 <    public void joinPool(ExecutorService exec) {
491 >    void joinPool(ExecutorService exec) {
492          try {
493              exec.shutdown();
494 <            assertTrue(exec.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
494 >            assertTrue("ExecutorService did not terminate in a timely manner",
495 >                       exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS));
496          } catch (SecurityException ok) {
497              // Allowed in case test doesn't have privs
498          } catch (InterruptedException ie) {
# Line 340 | Line 500 | public class JSR166TestCase extends Test
500          }
501      }
502  
343
503      /**
504 <     * fail with message "should throw exception"
504 >     * Checks that thread does not terminate within the default
505 >     * millisecond delay of {@code timeoutMillis()}.
506       */
507 <    public void shouldThrow() {
508 <        fail("Should throw exception");
507 >    void assertThreadStaysAlive(Thread thread) {
508 >        assertThreadStaysAlive(thread, timeoutMillis());
509      }
510  
511      /**
512 <     * fail with message "should throw " + exceptionName
512 >     * Checks that thread does not terminate within the given millisecond delay.
513       */
514 <    public void shouldThrow(String exceptionName) {
515 <        fail("Should throw " + exceptionName);
514 >    void assertThreadStaysAlive(Thread thread, long millis) {
515 >        try {
516 >            // No need to optimize the failing case via Thread.join.
517 >            delay(millis);
518 >            assertTrue(thread.isAlive());
519 >        } catch (InterruptedException ie) {
520 >            fail("Unexpected InterruptedException");
521 >        }
522      }
523  
524      /**
525 <     * fail with message "Unexpected exception"
525 >     * Fails with message "should throw exception".
526       */
527 <    public void unexpectedException() {
528 <        fail("Unexpected exception");
527 >    public void shouldThrow() {
528 >        fail("Should throw exception");
529      }
530  
531      /**
532 <     * fail with message "Unexpected exception", with argument
532 >     * Fails with message "should throw " + exceptionName.
533       */
534 <    public void unexpectedException(Throwable ex) {
535 <        ex.printStackTrace();
370 <        fail("Unexpected exception: " + ex);
534 >    public void shouldThrow(String exceptionName) {
535 >        fail("Should throw " + exceptionName);
536      }
537  
373
538      /**
539       * The number of elements to place in collections, arrays, etc.
540       */
# Line 482 | Line 646 | public class JSR166TestCase extends Test
646      }
647  
648      /**
649 <     * Sleep until the timeout has elapsed, or interrupted.
650 <     * Does <em>NOT</em> throw InterruptedException.
649 >     * Sleeps until the given time has elapsed.
650 >     * Throws AssertionFailedError if interrupted.
651       */
652 <    void sleepTillInterrupted(long timeoutMillis) {
652 >    void sleep(long millis) {
653          try {
654 <            Thread.sleep(timeoutMillis);
655 <        } catch (InterruptedException wakeup) {}
654 >            delay(millis);
655 >        } catch (InterruptedException ie) {
656 >            AssertionFailedError afe =
657 >                new AssertionFailedError("Unexpected InterruptedException");
658 >            afe.initCause(ie);
659 >            throw afe;
660 >        }
661 >    }
662 >
663 >    /**
664 >     * Waits up to the specified number of milliseconds for the given
665 >     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
666 >     */
667 >    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
668 >        long timeoutNanos = timeoutMillis * 1000L * 1000L;
669 >        long t0 = System.nanoTime();
670 >        for (;;) {
671 >            Thread.State s = thread.getState();
672 >            if (s == Thread.State.BLOCKED ||
673 >                s == Thread.State.WAITING ||
674 >                s == Thread.State.TIMED_WAITING)
675 >                return;
676 >            else if (s == Thread.State.TERMINATED)
677 >                fail("Unexpected thread termination");
678 >            else if (System.nanoTime() - t0 > timeoutNanos) {
679 >                threadAssertTrue(thread.isAlive());
680 >                return;
681 >            }
682 >            Thread.yield();
683 >        }
684      }
685  
686      /**
687 <     * Returns a new started Thread running the given runnable.
687 >     * Waits up to LONG_DELAY_MS for the given thread to enter a wait
688 >     * state: BLOCKED, WAITING, or TIMED_WAITING.
689 >     */
690 >    void waitForThreadToEnterWaitState(Thread thread) {
691 >        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
692 >    }
693 >
694 >    /**
695 >     * Returns the number of milliseconds since time given by
696 >     * startNanoTime, which must have been previously returned from a
697 >     * call to {@link System.nanoTime()}.
698 >     */
699 >    long millisElapsedSince(long startNanoTime) {
700 >        return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
701 >    }
702 >
703 >    /**
704 >     * Returns a new started daemon Thread running the given runnable.
705       */
706      Thread newStartedThread(Runnable runnable) {
707          Thread t = new Thread(runnable);
708 +        t.setDaemon(true);
709          t.start();
710          return t;
711      }
712  
713 +    /**
714 +     * Waits for the specified time (in milliseconds) for the thread
715 +     * to terminate (using {@link Thread#join(long)}), else interrupts
716 +     * the thread (in the hope that it may terminate later) and fails.
717 +     */
718 +    void awaitTermination(Thread t, long timeoutMillis) {
719 +        try {
720 +            t.join(timeoutMillis);
721 +        } catch (InterruptedException ie) {
722 +            threadUnexpectedException(ie);
723 +        } finally {
724 +            if (t.isAlive()) {
725 +                t.interrupt();
726 +                fail("Test timed out");
727 +            }
728 +        }
729 +    }
730 +
731 +    /**
732 +     * Waits for LONG_DELAY_MS milliseconds for the thread to
733 +     * terminate (using {@link Thread#join(long)}), else interrupts
734 +     * the thread (in the hope that it may terminate later) and fails.
735 +     */
736 +    void awaitTermination(Thread t) {
737 +        awaitTermination(t, LONG_DELAY_MS);
738 +    }
739 +
740      // Some convenient Runnable classes
741  
742      public abstract class CheckedRunnable implements Runnable {
# Line 562 | Line 799 | public class JSR166TestCase extends Test
799                  realRun();
800                  threadShouldThrow("InterruptedException");
801              } catch (InterruptedException success) {
802 +                threadAssertFalse(Thread.interrupted());
803              } catch (Throwable t) {
804                  threadUnexpectedException(t);
805              }
# Line 576 | Line 814 | public class JSR166TestCase extends Test
814                  return realCall();
815              } catch (Throwable t) {
816                  threadUnexpectedException(t);
817 +                return null;
818              }
580            return null;
819          }
820      }
821  
822 <    public abstract class CheckedInterruptedCallable<T> implements Callable<T> {
822 >    public abstract class CheckedInterruptedCallable<T>
823 >        implements Callable<T> {
824          protected abstract T realCall() throws Throwable;
825  
826          public final T call() {
# Line 590 | Line 829 | public class JSR166TestCase extends Test
829                  threadShouldThrow("InterruptedException");
830                  return result;
831              } catch (InterruptedException success) {
832 +                threadAssertFalse(Thread.interrupted());
833              } catch (Throwable t) {
834                  threadUnexpectedException(t);
835              }
# Line 613 | Line 853 | public class JSR166TestCase extends Test
853  
854      public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
855          return new CheckedCallable<String>() {
856 <            public String realCall() {
856 >            protected String realCall() {
857                  try {
858                      latch.await();
859                  } catch (InterruptedException quittingTime) {}
# Line 621 | Line 861 | public class JSR166TestCase extends Test
861              }};
862      }
863  
864 +    public Runnable awaiter(final CountDownLatch latch) {
865 +        return new CheckedRunnable() {
866 +            public void realRun() throws InterruptedException {
867 +                await(latch);
868 +            }};
869 +    }
870 +
871 +    public void await(CountDownLatch latch) {
872 +        try {
873 +            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
874 +        } catch (Throwable t) {
875 +            threadUnexpectedException(t);
876 +        }
877 +    }
878 +
879 + //     /**
880 + //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
881 + //      */
882 + //     public void await(AtomicBoolean flag) {
883 + //         await(flag, LONG_DELAY_MS);
884 + //     }
885 +
886 + //     /**
887 + //      * Spin-waits up to the specified timeout until flag becomes true.
888 + //      */
889 + //     public void await(AtomicBoolean flag, long timeoutMillis) {
890 + //         long startTime = System.nanoTime();
891 + //         while (!flag.get()) {
892 + //             if (millisElapsedSince(startTime) > timeoutMillis)
893 + //                 throw new AssertionFailedError("timed out");
894 + //             Thread.yield();
895 + //         }
896 + //     }
897 +
898      public static class NPETask implements Callable<String> {
899          public String call() { throw new NullPointerException(); }
900      }
# Line 631 | Line 905 | public class JSR166TestCase extends Test
905  
906      public class ShortRunnable extends CheckedRunnable {
907          protected void realRun() throws Throwable {
908 <            Thread.sleep(SHORT_DELAY_MS);
908 >            delay(SHORT_DELAY_MS);
909          }
910      }
911  
912      public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
913          protected void realRun() throws InterruptedException {
914 <            Thread.sleep(SHORT_DELAY_MS);
914 >            delay(SHORT_DELAY_MS);
915          }
916      }
917  
918      public class SmallRunnable extends CheckedRunnable {
919          protected void realRun() throws Throwable {
920 <            Thread.sleep(SMALL_DELAY_MS);
920 >            delay(SMALL_DELAY_MS);
921          }
922      }
923  
924      public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
925          protected void realRun() {
926              try {
927 <                Thread.sleep(SMALL_DELAY_MS);
927 >                delay(SMALL_DELAY_MS);
928              } catch (InterruptedException ok) {}
929          }
930      }
931  
932      public class SmallCallable extends CheckedCallable {
933          protected Object realCall() throws InterruptedException {
934 <            Thread.sleep(SMALL_DELAY_MS);
934 >            delay(SMALL_DELAY_MS);
935              return Boolean.TRUE;
936          }
937      }
938  
665    public class SmallInterruptedRunnable extends CheckedInterruptedRunnable {
666        protected void realRun() throws InterruptedException {
667            Thread.sleep(SMALL_DELAY_MS);
668        }
669    }
670
939      public class MediumRunnable extends CheckedRunnable {
940          protected void realRun() throws Throwable {
941 <            Thread.sleep(MEDIUM_DELAY_MS);
941 >            delay(MEDIUM_DELAY_MS);
942          }
943      }
944  
945      public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
946          protected void realRun() throws InterruptedException {
947 <            Thread.sleep(MEDIUM_DELAY_MS);
947 >            delay(MEDIUM_DELAY_MS);
948          }
949      }
950  
951 +    public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
952 +        return new CheckedRunnable() {
953 +            protected void realRun() {
954 +                try {
955 +                    delay(timeoutMillis);
956 +                } catch (InterruptedException ok) {}
957 +            }};
958 +    }
959 +
960      public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
961          protected void realRun() {
962              try {
963 <                Thread.sleep(MEDIUM_DELAY_MS);
963 >                delay(MEDIUM_DELAY_MS);
964              } catch (InterruptedException ok) {}
965          }
966      }
# Line 691 | Line 968 | public class JSR166TestCase extends Test
968      public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
969          protected void realRun() {
970              try {
971 <                Thread.sleep(LONG_DELAY_MS);
971 >                delay(LONG_DELAY_MS);
972              } catch (InterruptedException ok) {}
973          }
974      }
# Line 705 | Line 982 | public class JSR166TestCase extends Test
982          }
983      }
984  
985 +    public interface TrackedRunnable extends Runnable {
986 +        boolean isDone();
987 +    }
988 +
989 +    public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
990 +        return new TrackedRunnable() {
991 +                private volatile boolean done = false;
992 +                public boolean isDone() { return done; }
993 +                public void run() {
994 +                    try {
995 +                        delay(timeoutMillis);
996 +                        done = true;
997 +                    } catch (InterruptedException ok) {}
998 +                }
999 +            };
1000 +    }
1001 +
1002      public static class TrackedShortRunnable implements Runnable {
1003          public volatile boolean done = false;
1004          public void run() {
1005              try {
1006 <                Thread.sleep(SMALL_DELAY_MS);
1006 >                delay(SHORT_DELAY_MS);
1007 >                done = true;
1008 >            } catch (InterruptedException ok) {}
1009 >        }
1010 >    }
1011 >
1012 >    public static class TrackedSmallRunnable implements Runnable {
1013 >        public volatile boolean done = false;
1014 >        public void run() {
1015 >            try {
1016 >                delay(SMALL_DELAY_MS);
1017                  done = true;
1018              } catch (InterruptedException ok) {}
1019          }
# Line 719 | Line 1023 | public class JSR166TestCase extends Test
1023          public volatile boolean done = false;
1024          public void run() {
1025              try {
1026 <                Thread.sleep(MEDIUM_DELAY_MS);
1026 >                delay(MEDIUM_DELAY_MS);
1027                  done = true;
1028              } catch (InterruptedException ok) {}
1029          }
# Line 729 | Line 1033 | public class JSR166TestCase extends Test
1033          public volatile boolean done = false;
1034          public void run() {
1035              try {
1036 <                Thread.sleep(LONG_DELAY_MS);
1036 >                delay(LONG_DELAY_MS);
1037                  done = true;
1038              } catch (InterruptedException ok) {}
1039          }
# Line 746 | Line 1050 | public class JSR166TestCase extends Test
1050          public volatile boolean done = false;
1051          public Object call() {
1052              try {
1053 <                Thread.sleep(SMALL_DELAY_MS);
1053 >                delay(SMALL_DELAY_MS);
1054                  done = true;
1055              } catch (InterruptedException ok) {}
1056              return Boolean.TRUE;
1057          }
1058      }
1059  
1060 +    /**
1061 +     * Analog of CheckedRunnable for RecursiveAction
1062 +     */
1063 +    public abstract class CheckedRecursiveAction extends RecursiveAction {
1064 +        protected abstract void realCompute() throws Throwable;
1065 +
1066 +        public final void compute() {
1067 +            try {
1068 +                realCompute();
1069 +            } catch (Throwable t) {
1070 +                threadUnexpectedException(t);
1071 +            }
1072 +        }
1073 +    }
1074 +
1075 +    /**
1076 +     * Analog of CheckedCallable for RecursiveTask
1077 +     */
1078 +    public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1079 +        protected abstract T realCompute() throws Throwable;
1080 +
1081 +        public final T compute() {
1082 +            try {
1083 +                return realCompute();
1084 +            } catch (Throwable t) {
1085 +                threadUnexpectedException(t);
1086 +                return null;
1087 +            }
1088 +        }
1089 +    }
1090  
1091      /**
1092       * For use as RejectedExecutionHandler in constructors
# Line 762 | Line 1096 | public class JSR166TestCase extends Test
1096                                        ThreadPoolExecutor executor) {}
1097      }
1098  
1099 +    /**
1100 +     * A CyclicBarrier that fails with AssertionFailedErrors instead
1101 +     * of throwing checked exceptions.
1102 +     */
1103 +    public class CheckedBarrier extends CyclicBarrier {
1104 +        public CheckedBarrier(int parties) { super(parties); }
1105 +
1106 +        public int await() {
1107 +            try {
1108 +                return super.await();
1109 +            } catch (Exception e) {
1110 +                AssertionFailedError afe =
1111 +                    new AssertionFailedError("Unexpected exception: " + e);
1112 +                afe.initCause(e);
1113 +                throw afe;
1114 +            }
1115 +        }
1116 +    }
1117 +
1118 +    void checkEmpty(BlockingQueue q) {
1119 +        try {
1120 +            assertTrue(q.isEmpty());
1121 +            assertEquals(0, q.size());
1122 +            assertNull(q.peek());
1123 +            assertNull(q.poll());
1124 +            assertNull(q.poll(0, MILLISECONDS));
1125 +            assertEquals(q.toString(), "[]");
1126 +            assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1127 +            assertFalse(q.iterator().hasNext());
1128 +            try {
1129 +                q.element();
1130 +                shouldThrow();
1131 +            } catch (NoSuchElementException success) {}
1132 +            try {
1133 +                q.iterator().next();
1134 +                shouldThrow();
1135 +            } catch (NoSuchElementException success) {}
1136 +            try {
1137 +                q.remove();
1138 +                shouldThrow();
1139 +            } catch (NoSuchElementException success) {}
1140 +        } catch (InterruptedException ie) {
1141 +            threadUnexpectedException(ie);
1142 +        }
1143 +    }
1144 +
1145 +    @SuppressWarnings("unchecked")
1146 +    <T> T serialClone(T o) {
1147 +        try {
1148 +            ByteArrayOutputStream bos = new ByteArrayOutputStream();
1149 +            ObjectOutputStream oos = new ObjectOutputStream(bos);
1150 +            oos.writeObject(o);
1151 +            oos.flush();
1152 +            oos.close();
1153 +            ByteArrayInputStream bin =
1154 +                new ByteArrayInputStream(bos.toByteArray());
1155 +            ObjectInputStream ois = new ObjectInputStream(bin);
1156 +            return (T) ois.readObject();
1157 +        } catch (Throwable t) {
1158 +            threadUnexpectedException(t);
1159 +            return null;
1160 +        }
1161 +    }
1162   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines