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.52 by jsr166, Mon Sep 13 23:19:31 2010 UTC vs.
Revision 1.78 by jsr166, Sat May 7 19:03:26 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.util.Arrays;
11 > import java.util.NoSuchElementException;
12 > import java.util.PropertyPermission;
13   import java.util.concurrent.*;
14 + import java.util.concurrent.atomic.AtomicReference;
15   import static java.util.concurrent.TimeUnit.MILLISECONDS;
16 < import java.io.*;
17 < import java.security.*;
16 > import static java.util.concurrent.TimeUnit.NANOSECONDS;
17 > import java.security.CodeSource;
18 > import java.security.Permission;
19 > import java.security.PermissionCollection;
20 > import java.security.Permissions;
21 > import java.security.Policy;
22 > import java.security.ProtectionDomain;
23 > import java.security.SecurityPermission;
24  
25   /**
26   * Base class for JSR166 Junit TCK tests.  Defines some constants,
# Line 90 | Line 99 | public class JSR166TestCase extends Test
99      private static final boolean useSecurityManager =
100          Boolean.getBoolean("jsr166.useSecurityManager");
101  
102 +    protected static final boolean expensiveTests =
103 +        Boolean.getBoolean("jsr166.expensiveTests");
104 +
105 +    /**
106 +     * If true, report on stdout all "slow" tests, that is, ones that
107 +     * take more than profileThreshold milliseconds to execute.
108 +     */
109 +    private static final boolean profileTests =
110 +        Boolean.getBoolean("jsr166.profileTests");
111 +
112 +    /**
113 +     * The number of milliseconds that tests are permitted for
114 +     * execution without being reported, when profileTests is set.
115 +     */
116 +    private static final long profileThreshold =
117 +        Long.getLong("jsr166.profileThreshold", 100);
118 +
119 +    protected void runTest() throws Throwable {
120 +        if (profileTests)
121 +            runTestProfiled();
122 +        else
123 +            super.runTest();
124 +    }
125 +
126 +    protected void runTestProfiled() throws Throwable {
127 +        long t0 = System.nanoTime();
128 +        try {
129 +            super.runTest();
130 +        } finally {
131 +            long elapsedMillis =
132 +                (System.nanoTime() - t0) / (1000L * 1000L);
133 +            if (elapsedMillis >= profileThreshold)
134 +                System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
135 +        }
136 +    }
137 +
138      /**
139       * Runs all JSR166 unit tests using junit.textui.TestRunner
140       */
# Line 99 | Line 144 | public class JSR166TestCase extends Test
144              Policy.setPolicy(permissivePolicy());
145              System.setSecurityManager(new SecurityManager());
146          }
147 <        int iters = 1;
148 <        if (args.length > 0)
104 <            iters = Integer.parseInt(args[0]);
147 >        int iters = (args.length == 0) ? 1 : Integer.parseInt(args[0]);
148 >
149          Test s = suite();
150          for (int i = 0; i < iters; ++i) {
151              junit.textui.TestRunner.run(s);
# Line 111 | Line 155 | public class JSR166TestCase extends Test
155          System.exit(0);
156      }
157  
158 +    public static TestSuite newTestSuite(Object... suiteOrClasses) {
159 +        TestSuite suite = new TestSuite();
160 +        for (Object suiteOrClass : suiteOrClasses) {
161 +            if (suiteOrClass instanceof TestSuite)
162 +                suite.addTest((TestSuite) suiteOrClass);
163 +            else if (suiteOrClass instanceof Class)
164 +                suite.addTest(new TestSuite((Class<?>) suiteOrClass));
165 +            else
166 +                throw new ClassCastException("not a test suite or class");
167 +        }
168 +        return suite;
169 +    }
170 +
171      /**
172 <     * Collects all JSR166 unit tests as one suite
172 >     * Collects all JSR166 unit tests as one suite.
173       */
174      public static Test suite() {
175 <        TestSuite suite = new TestSuite("JSR166 Unit Tests");
176 <
177 <        suite.addTest(new TestSuite(ForkJoinPoolTest.class));
178 <        suite.addTest(new TestSuite(ForkJoinTaskTest.class));
179 <        suite.addTest(new TestSuite(RecursiveActionTest.class));
180 <        suite.addTest(new TestSuite(RecursiveTaskTest.class));
181 <        suite.addTest(new TestSuite(LinkedTransferQueueTest.class));
182 <        suite.addTest(new TestSuite(PhaserTest.class));
183 <        suite.addTest(new TestSuite(ThreadLocalRandomTest.class));
184 <        suite.addTest(new TestSuite(AbstractExecutorServiceTest.class));
185 <        suite.addTest(new TestSuite(AbstractQueueTest.class));
186 <        suite.addTest(new TestSuite(AbstractQueuedSynchronizerTest.class));
187 <        suite.addTest(new TestSuite(AbstractQueuedLongSynchronizerTest.class));
188 <        suite.addTest(new TestSuite(ArrayBlockingQueueTest.class));
189 <        suite.addTest(new TestSuite(ArrayDequeTest.class));
190 <        suite.addTest(new TestSuite(AtomicBooleanTest.class));
191 <        suite.addTest(new TestSuite(AtomicIntegerArrayTest.class));
192 <        suite.addTest(new TestSuite(AtomicIntegerFieldUpdaterTest.class));
193 <        suite.addTest(new TestSuite(AtomicIntegerTest.class));
194 <        suite.addTest(new TestSuite(AtomicLongArrayTest.class));
195 <        suite.addTest(new TestSuite(AtomicLongFieldUpdaterTest.class));
196 <        suite.addTest(new TestSuite(AtomicLongTest.class));
197 <        suite.addTest(new TestSuite(AtomicMarkableReferenceTest.class));
198 <        suite.addTest(new TestSuite(AtomicReferenceArrayTest.class));
199 <        suite.addTest(new TestSuite(AtomicReferenceFieldUpdaterTest.class));
200 <        suite.addTest(new TestSuite(AtomicReferenceTest.class));
201 <        suite.addTest(new TestSuite(AtomicStampedReferenceTest.class));
202 <        suite.addTest(new TestSuite(ConcurrentHashMapTest.class));
203 <        suite.addTest(new TestSuite(ConcurrentLinkedDequeTest.class));
204 <        suite.addTest(new TestSuite(ConcurrentLinkedQueueTest.class));
205 <        suite.addTest(new TestSuite(ConcurrentSkipListMapTest.class));
206 <        suite.addTest(new TestSuite(ConcurrentSkipListSubMapTest.class));
207 <        suite.addTest(new TestSuite(ConcurrentSkipListSetTest.class));
208 <        suite.addTest(new TestSuite(ConcurrentSkipListSubSetTest.class));
209 <        suite.addTest(new TestSuite(CopyOnWriteArrayListTest.class));
210 <        suite.addTest(new TestSuite(CopyOnWriteArraySetTest.class));
211 <        suite.addTest(new TestSuite(CountDownLatchTest.class));
212 <        suite.addTest(new TestSuite(CyclicBarrierTest.class));
213 <        suite.addTest(new TestSuite(DelayQueueTest.class));
214 <        suite.addTest(new TestSuite(EntryTest.class));
215 <        suite.addTest(new TestSuite(ExchangerTest.class));
216 <        suite.addTest(new TestSuite(ExecutorsTest.class));
217 <        suite.addTest(new TestSuite(ExecutorCompletionServiceTest.class));
218 <        suite.addTest(new TestSuite(FutureTaskTest.class));
219 <        suite.addTest(new TestSuite(LinkedBlockingDequeTest.class));
220 <        suite.addTest(new TestSuite(LinkedBlockingQueueTest.class));
221 <        suite.addTest(new TestSuite(LinkedListTest.class));
222 <        suite.addTest(new TestSuite(LockSupportTest.class));
223 <        suite.addTest(new TestSuite(PriorityBlockingQueueTest.class));
224 <        suite.addTest(new TestSuite(PriorityQueueTest.class));
225 <        suite.addTest(new TestSuite(ReentrantLockTest.class));
226 <        suite.addTest(new TestSuite(ReentrantReadWriteLockTest.class));
227 <        suite.addTest(new TestSuite(ScheduledExecutorTest.class));
228 <        suite.addTest(new TestSuite(ScheduledExecutorSubclassTest.class));
229 <        suite.addTest(new TestSuite(SemaphoreTest.class));
230 <        suite.addTest(new TestSuite(SynchronousQueueTest.class));
231 <        suite.addTest(new TestSuite(SystemTest.class));
232 <        suite.addTest(new TestSuite(ThreadLocalTest.class));
233 <        suite.addTest(new TestSuite(ThreadPoolExecutorTest.class));
234 <        suite.addTest(new TestSuite(ThreadPoolExecutorSubclassTest.class));
235 <        suite.addTest(new TestSuite(ThreadTest.class));
236 <        suite.addTest(new TestSuite(TimeUnitTest.class));
237 <        suite.addTest(new TestSuite(TreeMapTest.class));
238 <        suite.addTest(new TestSuite(TreeSetTest.class));
239 <        suite.addTest(new TestSuite(TreeSubMapTest.class));
183 <        suite.addTest(new TestSuite(TreeSubSetTest.class));
184 <
185 <        return suite;
175 >        return newTestSuite(
176 >            ForkJoinPoolTest.suite(),
177 >            ForkJoinTaskTest.suite(),
178 >            RecursiveActionTest.suite(),
179 >            RecursiveTaskTest.suite(),
180 >            LinkedTransferQueueTest.suite(),
181 >            PhaserTest.suite(),
182 >            ThreadLocalRandomTest.suite(),
183 >            AbstractExecutorServiceTest.suite(),
184 >            AbstractQueueTest.suite(),
185 >            AbstractQueuedSynchronizerTest.suite(),
186 >            AbstractQueuedLongSynchronizerTest.suite(),
187 >            ArrayBlockingQueueTest.suite(),
188 >            ArrayDequeTest.suite(),
189 >            AtomicBooleanTest.suite(),
190 >            AtomicIntegerArrayTest.suite(),
191 >            AtomicIntegerFieldUpdaterTest.suite(),
192 >            AtomicIntegerTest.suite(),
193 >            AtomicLongArrayTest.suite(),
194 >            AtomicLongFieldUpdaterTest.suite(),
195 >            AtomicLongTest.suite(),
196 >            AtomicMarkableReferenceTest.suite(),
197 >            AtomicReferenceArrayTest.suite(),
198 >            AtomicReferenceFieldUpdaterTest.suite(),
199 >            AtomicReferenceTest.suite(),
200 >            AtomicStampedReferenceTest.suite(),
201 >            ConcurrentHashMapTest.suite(),
202 >            ConcurrentLinkedDequeTest.suite(),
203 >            ConcurrentLinkedQueueTest.suite(),
204 >            ConcurrentSkipListMapTest.suite(),
205 >            ConcurrentSkipListSubMapTest.suite(),
206 >            ConcurrentSkipListSetTest.suite(),
207 >            ConcurrentSkipListSubSetTest.suite(),
208 >            CopyOnWriteArrayListTest.suite(),
209 >            CopyOnWriteArraySetTest.suite(),
210 >            CountDownLatchTest.suite(),
211 >            CyclicBarrierTest.suite(),
212 >            DelayQueueTest.suite(),
213 >            EntryTest.suite(),
214 >            ExchangerTest.suite(),
215 >            ExecutorsTest.suite(),
216 >            ExecutorCompletionServiceTest.suite(),
217 >            FutureTaskTest.suite(),
218 >            LinkedBlockingDequeTest.suite(),
219 >            LinkedBlockingQueueTest.suite(),
220 >            LinkedListTest.suite(),
221 >            LockSupportTest.suite(),
222 >            PriorityBlockingQueueTest.suite(),
223 >            PriorityQueueTest.suite(),
224 >            ReentrantLockTest.suite(),
225 >            ReentrantReadWriteLockTest.suite(),
226 >            ScheduledExecutorTest.suite(),
227 >            ScheduledExecutorSubclassTest.suite(),
228 >            SemaphoreTest.suite(),
229 >            SynchronousQueueTest.suite(),
230 >            SystemTest.suite(),
231 >            ThreadLocalTest.suite(),
232 >            ThreadPoolExecutorTest.suite(),
233 >            ThreadPoolExecutorSubclassTest.suite(),
234 >            ThreadTest.suite(),
235 >            TimeUnitTest.suite(),
236 >            TreeMapTest.suite(),
237 >            TreeSetTest.suite(),
238 >            TreeSubMapTest.suite(),
239 >            TreeSubSetTest.suite());
240      }
241  
242  
# Line 206 | Line 260 | public class JSR166TestCase extends Test
260       */
261      protected void setDelays() {
262          SHORT_DELAY_MS = getShortDelay();
263 <        SMALL_DELAY_MS = SHORT_DELAY_MS * 5;
263 >        SMALL_DELAY_MS  = SHORT_DELAY_MS * 5;
264          MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
265 <        LONG_DELAY_MS = SHORT_DELAY_MS * 50;
265 >        LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
266      }
267  
268      /**
269 <     * Flag set true if any threadAssert methods fail
269 >     * The first exception encountered if any threadAssertXXX method fails.
270       */
271 <    volatile boolean threadFailed;
271 >    private final AtomicReference<Throwable> threadFailure
272 >        = new AtomicReference<Throwable>(null);
273  
274      /**
275 <     * Initializes test to indicate that no thread assertions have failed
275 >     * Records an exception so that it can be rethrown later in the test
276 >     * harness thread, triggering a test case failure.  Only the first
277 >     * failure is recorded; subsequent calls to this method from within
278 >     * the same test have no effect.
279       */
280 +    public void threadRecordFailure(Throwable t) {
281 +        threadFailure.compareAndSet(null, t);
282 +    }
283 +
284      public void setUp() {
285          setDelays();
224        threadFailed = false;
286      }
287  
288      /**
289 <     * Triggers test case failure if any thread assertions have failed
290 <     */
291 <    public void tearDown() {
292 <        assertFalse(threadFailed);
289 >     * Triggers test case failure if any thread assertions have failed,
290 >     * by rethrowing, in the test harness thread, any exception recorded
291 >     * earlier by threadRecordFailure.
292 >     */
293 >    public void tearDown() throws Exception {
294 >        Throwable t = threadFailure.getAndSet(null);
295 >        if (t != null) {
296 >            if (t instanceof Error)
297 >                throw (Error) t;
298 >            else if (t instanceof RuntimeException)
299 >                throw (RuntimeException) t;
300 >            else if (t instanceof Exception)
301 >                throw (Exception) t;
302 >            else {
303 >                AssertionFailedError afe =
304 >                    new AssertionFailedError(t.toString());
305 >                afe.initCause(t);
306 >                throw afe;
307 >            }
308 >        }
309      }
310  
311      /**
312 <     * Fail, also setting status to indicate current testcase should fail
312 >     * Just like fail(reason), but additionally recording (using
313 >     * threadRecordFailure) any AssertionFailedError thrown, so that
314 >     * the current testcase will fail.
315       */
316      public void threadFail(String reason) {
317 <        threadFailed = true;
318 <        fail(reason);
317 >        try {
318 >            fail(reason);
319 >        } catch (AssertionFailedError t) {
320 >            threadRecordFailure(t);
321 >            fail(reason);
322 >        }
323      }
324  
325      /**
326 <     * If expression not true, set status to indicate current testcase
327 <     * should fail
326 >     * Just like assertTrue(b), but additionally recording (using
327 >     * threadRecordFailure) any AssertionFailedError thrown, so that
328 >     * the current testcase will fail.
329       */
330      public void threadAssertTrue(boolean b) {
331 <        if (!b) {
248 <            threadFailed = true;
331 >        try {
332              assertTrue(b);
333 +        } catch (AssertionFailedError t) {
334 +            threadRecordFailure(t);
335 +            throw t;
336          }
337      }
338  
339      /**
340 <     * If expression not false, set status to indicate current testcase
341 <     * should fail
340 >     * Just like assertFalse(b), but additionally recording (using
341 >     * threadRecordFailure) any AssertionFailedError thrown, so that
342 >     * the current testcase will fail.
343       */
344      public void threadAssertFalse(boolean b) {
345 <        if (b) {
259 <            threadFailed = true;
345 >        try {
346              assertFalse(b);
347 +        } catch (AssertionFailedError t) {
348 +            threadRecordFailure(t);
349 +            throw t;
350          }
351      }
352  
353      /**
354 <     * If argument not null, set status to indicate current testcase
355 <     * should fail
354 >     * Just like assertNull(x), but additionally recording (using
355 >     * threadRecordFailure) any AssertionFailedError thrown, so that
356 >     * the current testcase will fail.
357       */
358      public void threadAssertNull(Object x) {
359 <        if (x != null) {
270 <            threadFailed = true;
359 >        try {
360              assertNull(x);
361 +        } catch (AssertionFailedError t) {
362 +            threadRecordFailure(t);
363 +            throw t;
364          }
365      }
366  
367      /**
368 <     * If arguments not equal, set status to indicate current testcase
369 <     * should fail
368 >     * Just like assertEquals(x, y), but additionally recording (using
369 >     * threadRecordFailure) any AssertionFailedError thrown, so that
370 >     * the current testcase will fail.
371       */
372      public void threadAssertEquals(long x, long y) {
373 <        if (x != y) {
281 <            threadFailed = true;
373 >        try {
374              assertEquals(x, y);
375 +        } catch (AssertionFailedError t) {
376 +            threadRecordFailure(t);
377 +            throw t;
378          }
379      }
380  
381      /**
382 <     * If arguments not equal, set status to indicate current testcase
383 <     * should fail
382 >     * Just like assertEquals(x, y), but additionally recording (using
383 >     * threadRecordFailure) any AssertionFailedError thrown, so that
384 >     * the current testcase will fail.
385       */
386      public void threadAssertEquals(Object x, Object y) {
387 <        if (x != y && (x == null || !x.equals(y))) {
292 <            threadFailed = true;
387 >        try {
388              assertEquals(x, y);
389 +        } catch (AssertionFailedError t) {
390 +            threadRecordFailure(t);
391 +            throw t;
392 +        } catch (Throwable t) {
393 +            threadUnexpectedException(t);
394          }
395      }
396  
397      /**
398 <     * If arguments not identical, set status to indicate current testcase
399 <     * should fail
398 >     * Just like assertSame(x, y), but additionally recording (using
399 >     * threadRecordFailure) any AssertionFailedError thrown, so that
400 >     * the current testcase will fail.
401       */
402      public void threadAssertSame(Object x, Object y) {
403 <        if (x != y) {
303 <            threadFailed = true;
403 >        try {
404              assertSame(x, y);
405 +        } catch (AssertionFailedError t) {
406 +            threadRecordFailure(t);
407 +            throw t;
408          }
409      }
410  
411      /**
412 <     * threadFail with message "should throw exception"
412 >     * Calls threadFail with message "should throw exception".
413       */
414      public void threadShouldThrow() {
415 <        threadFailed = true;
313 <        fail("should throw exception");
415 >        threadFail("should throw exception");
416      }
417  
418      /**
419 <     * threadFail with message "should throw" + exceptionName
419 >     * Calls threadFail with message "should throw" + exceptionName.
420       */
421      public void threadShouldThrow(String exceptionName) {
422 <        threadFailed = true;
321 <        fail("should throw " + exceptionName);
422 >        threadFail("should throw " + exceptionName);
423      }
424  
425      /**
426 <     * threadFail with message "Unexpected exception"
426 >     * Records the given exception using {@link #threadRecordFailure},
427 >     * then rethrows the exception, wrapping it in an
428 >     * AssertionFailedError if necessary.
429       */
430 <    public void threadUnexpectedException() {
431 <        threadFailed = true;
432 <        fail("Unexpected exception");
430 >    public void threadUnexpectedException(Throwable t) {
431 >        threadRecordFailure(t);
432 >        t.printStackTrace();
433 >        if (t instanceof RuntimeException)
434 >            throw (RuntimeException) t;
435 >        else if (t instanceof Error)
436 >            throw (Error) t;
437 >        else {
438 >            AssertionFailedError afe =
439 >                new AssertionFailedError("unexpected exception: " + t);
440 >            t.initCause(t);
441 >            throw afe;
442 >        }
443      }
444  
445      /**
446 <     * threadFail with message "Unexpected exception", with argument
446 >     * Delays, via Thread.sleep for the given millisecond delay, but
447 >     * if the sleep is shorter than specified, may re-sleep or yield
448 >     * until time elapses.
449       */
450 <    public void threadUnexpectedException(Throwable ex) {
451 <        threadFailed = true;
452 <        ex.printStackTrace();
453 <        fail("Unexpected exception: " + ex);
450 >    public static void delay(long ms) throws InterruptedException {
451 >        long startTime = System.nanoTime();
452 >        long ns = ms * 1000 * 1000;
453 >        for (;;) {
454 >            if (ms > 0L)
455 >                Thread.sleep(ms);
456 >            else // too short to sleep
457 >                Thread.yield();
458 >            long d = ns - (System.nanoTime() - startTime);
459 >            if (d > 0L)
460 >                ms = d / (1000 * 1000);
461 >            else
462 >                break;
463 >        }
464      }
465  
466      /**
467 <     * Wait out termination of a thread pool or fail doing so
467 >     * Waits out termination of a thread pool or fails doing so.
468       */
469      public void joinPool(ExecutorService exec) {
470          try {
471              exec.shutdown();
472 <            assertTrue(exec.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
472 >            assertTrue("ExecutorService did not terminate in a timely manner",
473 >                       exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS));
474          } catch (SecurityException ok) {
475              // Allowed in case test doesn't have privs
476          } catch (InterruptedException ie) {
# Line 352 | Line 478 | public class JSR166TestCase extends Test
478          }
479      }
480  
481 +    /**
482 +     * Checks that thread does not terminate within timeoutMillis
483 +     * milliseconds (that is, Thread.join times out).
484 +     */
485 +    public void assertThreadJoinTimesOut(Thread thread, long timeoutMillis) {
486 +        try {
487 +            long startTime = System.nanoTime();
488 +            thread.join(timeoutMillis);
489 +            assertTrue(thread.isAlive());
490 +            assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
491 +        } catch (InterruptedException ie) {
492 +            fail("Unexpected InterruptedException");
493 +        }
494 +    }
495  
496      /**
497 <     * fail with message "should throw exception"
497 >     * Fails with message "should throw exception".
498       */
499      public void shouldThrow() {
500          fail("Should throw exception");
501      }
502  
503      /**
504 <     * fail with message "should throw " + exceptionName
504 >     * Fails with message "should throw " + exceptionName.
505       */
506      public void shouldThrow(String exceptionName) {
507          fail("Should throw " + exceptionName);
508      }
509  
510      /**
371     * fail with message "Unexpected exception"
372     */
373    public void unexpectedException() {
374        fail("Unexpected exception");
375    }
376
377    /**
378     * fail with message "Unexpected exception", with argument
379     */
380    public void unexpectedException(Throwable ex) {
381        ex.printStackTrace();
382        fail("Unexpected exception: " + ex);
383    }
384
385
386    /**
511       * The number of elements to place in collections, arrays, etc.
512       */
513      public static final int SIZE = 20;
# Line 494 | Line 618 | public class JSR166TestCase extends Test
618      }
619  
620      /**
621 <     * Sleep until the timeout has elapsed, or interrupted.
621 >     * Sleeps until the given time has elapsed.
622 >     * Throws AssertionFailedError if interrupted.
623 >     */
624 >    void sleep(long millis) {
625 >        try {
626 >            delay(millis);
627 >        } catch (InterruptedException ie) {
628 >            AssertionFailedError afe =
629 >                new AssertionFailedError("Unexpected InterruptedException");
630 >            afe.initCause(ie);
631 >            throw afe;
632 >        }
633 >    }
634 >
635 >    /**
636 >     * Sleeps until the timeout has elapsed, or interrupted.
637       * Does <em>NOT</em> throw InterruptedException.
638       */
639      void sleepTillInterrupted(long timeoutMillis) {
# Line 504 | Line 643 | public class JSR166TestCase extends Test
643      }
644  
645      /**
646 <     * Returns a new started Thread running the given runnable.
646 >     * Waits up to the specified number of milliseconds for the given
647 >     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
648 >     */
649 >    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
650 >        long timeoutNanos = timeoutMillis * 1000L * 1000L;
651 >        long t0 = System.nanoTime();
652 >        for (;;) {
653 >            Thread.State s = thread.getState();
654 >            if (s == Thread.State.BLOCKED ||
655 >                s == Thread.State.WAITING ||
656 >                s == Thread.State.TIMED_WAITING)
657 >                return;
658 >            else if (s == Thread.State.TERMINATED)
659 >                fail("Unexpected thread termination");
660 >            else if (System.nanoTime() - t0 > timeoutNanos) {
661 >                threadAssertTrue(thread.isAlive());
662 >                return;
663 >            }
664 >            Thread.yield();
665 >        }
666 >    }
667 >
668 >    /**
669 >     * Waits up to LONG_DELAY_MS for the given thread to enter a wait
670 >     * state: BLOCKED, WAITING, or TIMED_WAITING.
671 >     */
672 >    void waitForThreadToEnterWaitState(Thread thread) {
673 >        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
674 >    }
675 >
676 >    /**
677 >     * Returns the number of milliseconds since time given by
678 >     * startNanoTime, which must have been previously returned from a
679 >     * call to {@link System.nanoTime()}.
680 >     */
681 >    long millisElapsedSince(long startNanoTime) {
682 >        return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
683 >    }
684 >
685 >    /**
686 >     * Returns a new started daemon Thread running the given runnable.
687       */
688      Thread newStartedThread(Runnable runnable) {
689          Thread t = new Thread(runnable);
690 +        t.setDaemon(true);
691          t.start();
692          return t;
693      }
694  
695 +    /**
696 +     * Waits for the specified time (in milliseconds) for the thread
697 +     * to terminate (using {@link Thread#join(long)}), else interrupts
698 +     * the thread (in the hope that it may terminate later) and fails.
699 +     */
700 +    void awaitTermination(Thread t, long timeoutMillis) {
701 +        try {
702 +            t.join(timeoutMillis);
703 +        } catch (InterruptedException ie) {
704 +            threadUnexpectedException(ie);
705 +        } finally {
706 +            if (t.isAlive()) {
707 +                t.interrupt();
708 +                fail("Test timed out");
709 +            }
710 +        }
711 +    }
712 +
713 +    /**
714 +     * Waits for LONG_DELAY_MS milliseconds for the thread to
715 +     * 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) {
719 +        awaitTermination(t, LONG_DELAY_MS);
720 +    }
721 +
722      // Some convenient Runnable classes
723  
724      public abstract class CheckedRunnable implements Runnable {
# Line 588 | Line 795 | public class JSR166TestCase extends Test
795                  return realCall();
796              } catch (Throwable t) {
797                  threadUnexpectedException(t);
798 +                return null;
799              }
592            return null;
800          }
801      }
802  
803 <    public abstract class CheckedInterruptedCallable<T> implements Callable<T> {
803 >    public abstract class CheckedInterruptedCallable<T>
804 >        implements Callable<T> {
805          protected abstract T realCall() throws Throwable;
806  
807          public final T call() {
# Line 625 | Line 833 | public class JSR166TestCase extends Test
833  
834      public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
835          return new CheckedCallable<String>() {
836 <            public String realCall() {
836 >            protected String realCall() {
837                  try {
838                      latch.await();
839                  } catch (InterruptedException quittingTime) {}
# Line 633 | Line 841 | public class JSR166TestCase extends Test
841              }};
842      }
843  
844 +    public Runnable awaiter(final CountDownLatch latch) {
845 +        return new CheckedRunnable() {
846 +            public void realRun() throws InterruptedException {
847 +                latch.await();
848 +            }};
849 +    }
850 +
851      public static class NPETask implements Callable<String> {
852          public String call() { throw new NullPointerException(); }
853      }
# Line 643 | Line 858 | public class JSR166TestCase extends Test
858  
859      public class ShortRunnable extends CheckedRunnable {
860          protected void realRun() throws Throwable {
861 <            Thread.sleep(SHORT_DELAY_MS);
861 >            delay(SHORT_DELAY_MS);
862          }
863      }
864  
865      public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
866          protected void realRun() throws InterruptedException {
867 <            Thread.sleep(SHORT_DELAY_MS);
867 >            delay(SHORT_DELAY_MS);
868          }
869      }
870  
871      public class SmallRunnable extends CheckedRunnable {
872          protected void realRun() throws Throwable {
873 <            Thread.sleep(SMALL_DELAY_MS);
873 >            delay(SMALL_DELAY_MS);
874          }
875      }
876  
877      public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
878          protected void realRun() {
879              try {
880 <                Thread.sleep(SMALL_DELAY_MS);
880 >                delay(SMALL_DELAY_MS);
881              } catch (InterruptedException ok) {}
882          }
883      }
884  
885      public class SmallCallable extends CheckedCallable {
886          protected Object realCall() throws InterruptedException {
887 <            Thread.sleep(SMALL_DELAY_MS);
887 >            delay(SMALL_DELAY_MS);
888              return Boolean.TRUE;
889          }
890      }
891  
677    public class SmallInterruptedRunnable extends CheckedInterruptedRunnable {
678        protected void realRun() throws InterruptedException {
679            Thread.sleep(SMALL_DELAY_MS);
680        }
681    }
682
892      public class MediumRunnable extends CheckedRunnable {
893          protected void realRun() throws Throwable {
894 <            Thread.sleep(MEDIUM_DELAY_MS);
894 >            delay(MEDIUM_DELAY_MS);
895          }
896      }
897  
898      public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
899          protected void realRun() throws InterruptedException {
900 <            Thread.sleep(MEDIUM_DELAY_MS);
900 >            delay(MEDIUM_DELAY_MS);
901          }
902      }
903  
904 +    public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
905 +        return new CheckedRunnable() {
906 +            protected void realRun() {
907 +                try {
908 +                    delay(timeoutMillis);
909 +                } catch (InterruptedException ok) {}
910 +            }};
911 +    }
912 +
913      public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
914          protected void realRun() {
915              try {
916 <                Thread.sleep(MEDIUM_DELAY_MS);
916 >                delay(MEDIUM_DELAY_MS);
917              } catch (InterruptedException ok) {}
918          }
919      }
# Line 703 | Line 921 | public class JSR166TestCase extends Test
921      public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
922          protected void realRun() {
923              try {
924 <                Thread.sleep(LONG_DELAY_MS);
924 >                delay(LONG_DELAY_MS);
925              } catch (InterruptedException ok) {}
926          }
927      }
# Line 717 | Line 935 | public class JSR166TestCase extends Test
935          }
936      }
937  
938 +    public interface TrackedRunnable extends Runnable {
939 +        boolean isDone();
940 +    }
941 +
942 +    public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
943 +        return new TrackedRunnable() {
944 +                private volatile boolean done = false;
945 +                public boolean isDone() { return done; }
946 +                public void run() {
947 +                    try {
948 +                        delay(timeoutMillis);
949 +                        done = true;
950 +                    } catch (InterruptedException ok) {}
951 +                }
952 +            };
953 +    }
954 +
955      public static class TrackedShortRunnable implements Runnable {
956          public volatile boolean done = false;
957          public void run() {
958              try {
959 <                Thread.sleep(SMALL_DELAY_MS);
959 >                delay(SHORT_DELAY_MS);
960 >                done = true;
961 >            } catch (InterruptedException ok) {}
962 >        }
963 >    }
964 >
965 >    public static class TrackedSmallRunnable implements Runnable {
966 >        public volatile boolean done = false;
967 >        public void run() {
968 >            try {
969 >                delay(SMALL_DELAY_MS);
970                  done = true;
971              } catch (InterruptedException ok) {}
972          }
# Line 731 | Line 976 | public class JSR166TestCase extends Test
976          public volatile boolean done = false;
977          public void run() {
978              try {
979 <                Thread.sleep(MEDIUM_DELAY_MS);
979 >                delay(MEDIUM_DELAY_MS);
980                  done = true;
981              } catch (InterruptedException ok) {}
982          }
# Line 741 | Line 986 | public class JSR166TestCase extends Test
986          public volatile boolean done = false;
987          public void run() {
988              try {
989 <                Thread.sleep(LONG_DELAY_MS);
989 >                delay(LONG_DELAY_MS);
990                  done = true;
991              } catch (InterruptedException ok) {}
992          }
# Line 758 | Line 1003 | public class JSR166TestCase extends Test
1003          public volatile boolean done = false;
1004          public Object call() {
1005              try {
1006 <                Thread.sleep(SMALL_DELAY_MS);
1006 >                delay(SMALL_DELAY_MS);
1007                  done = true;
1008              } catch (InterruptedException ok) {}
1009              return Boolean.TRUE;
1010          }
1011      }
1012  
1013 +    /**
1014 +     * Analog of CheckedRunnable for RecursiveAction
1015 +     */
1016 +    public abstract class CheckedRecursiveAction extends RecursiveAction {
1017 +        protected abstract void realCompute() throws Throwable;
1018 +
1019 +        public final void compute() {
1020 +            try {
1021 +                realCompute();
1022 +            } catch (Throwable t) {
1023 +                threadUnexpectedException(t);
1024 +            }
1025 +        }
1026 +    }
1027 +
1028 +    /**
1029 +     * Analog of CheckedCallable for RecursiveTask
1030 +     */
1031 +    public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1032 +        protected abstract T realCompute() throws Throwable;
1033 +
1034 +        public final T compute() {
1035 +            try {
1036 +                return realCompute();
1037 +            } catch (Throwable t) {
1038 +                threadUnexpectedException(t);
1039 +                return null;
1040 +            }
1041 +        }
1042 +    }
1043  
1044      /**
1045       * For use as RejectedExecutionHandler in constructors
# Line 774 | Line 1049 | public class JSR166TestCase extends Test
1049                                        ThreadPoolExecutor executor) {}
1050      }
1051  
1052 +    /**
1053 +     * A CyclicBarrier that fails with AssertionFailedErrors instead
1054 +     * of throwing checked exceptions.
1055 +     */
1056 +    public class CheckedBarrier extends CyclicBarrier {
1057 +        public CheckedBarrier(int parties) { super(parties); }
1058 +
1059 +        public int await() {
1060 +            try {
1061 +                return super.await();
1062 +            } catch (Exception e) {
1063 +                AssertionFailedError afe =
1064 +                    new AssertionFailedError("Unexpected exception: " + e);
1065 +                afe.initCause(e);
1066 +                throw afe;
1067 +            }
1068 +        }
1069 +    }
1070 +
1071 +    public void checkEmpty(BlockingQueue q) {
1072 +        try {
1073 +            assertTrue(q.isEmpty());
1074 +            assertEquals(0, q.size());
1075 +            assertNull(q.peek());
1076 +            assertNull(q.poll());
1077 +            assertNull(q.poll(0, MILLISECONDS));
1078 +            assertEquals(q.toString(), "[]");
1079 +            assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1080 +            assertFalse(q.iterator().hasNext());
1081 +            try {
1082 +                q.element();
1083 +                shouldThrow();
1084 +            } catch (NoSuchElementException success) {}
1085 +            try {
1086 +                q.iterator().next();
1087 +                shouldThrow();
1088 +            } catch (NoSuchElementException success) {}
1089 +            try {
1090 +                q.remove();
1091 +                shouldThrow();
1092 +            } catch (NoSuchElementException success) {}
1093 +        } catch (InterruptedException ie) {
1094 +            threadUnexpectedException(ie);
1095 +        }
1096 +    }
1097 +
1098   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines