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.57 by jsr166, Mon Oct 4 05:45:19 2010 UTC vs.
Revision 1.89 by jsr166, Fri Jun 3 05:07:14 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.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 static java.util.concurrent.TimeUnit.NANOSECONDS;
23   import java.security.CodeSource;
24   import java.security.Permission;
25   import java.security.PermissionCollection;
# Line 96 | 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 116 | 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(ForkJoinPoolTest.suite());
184 <        suite.addTest(ForkJoinTaskTest.suite());
185 <        suite.addTest(RecursiveActionTest.suite());
186 <        suite.addTest(RecursiveTaskTest.suite());
187 <        suite.addTest(LinkedTransferQueueTest.suite());
188 <        suite.addTest(PhaserTest.suite());
189 <        suite.addTest(ThreadLocalRandomTest.suite());
190 <        suite.addTest(AbstractExecutorServiceTest.suite());
191 <        suite.addTest(AbstractQueueTest.suite());
192 <        suite.addTest(AbstractQueuedSynchronizerTest.suite());
193 <        suite.addTest(AbstractQueuedLongSynchronizerTest.suite());
194 <        suite.addTest(ArrayBlockingQueueTest.suite());
195 <        suite.addTest(ArrayDequeTest.suite());
196 <        suite.addTest(AtomicBooleanTest.suite());
197 <        suite.addTest(AtomicIntegerArrayTest.suite());
198 <        suite.addTest(AtomicIntegerFieldUpdaterTest.suite());
199 <        suite.addTest(AtomicIntegerTest.suite());
200 <        suite.addTest(AtomicLongArrayTest.suite());
201 <        suite.addTest(AtomicLongFieldUpdaterTest.suite());
202 <        suite.addTest(AtomicLongTest.suite());
203 <        suite.addTest(AtomicMarkableReferenceTest.suite());
204 <        suite.addTest(AtomicReferenceArrayTest.suite());
205 <        suite.addTest(AtomicReferenceFieldUpdaterTest.suite());
206 <        suite.addTest(AtomicReferenceTest.suite());
207 <        suite.addTest(AtomicStampedReferenceTest.suite());
208 <        suite.addTest(ConcurrentHashMapTest.suite());
209 <        suite.addTest(ConcurrentLinkedDequeTest.suite());
210 <        suite.addTest(ConcurrentLinkedQueueTest.suite());
211 <        suite.addTest(ConcurrentSkipListMapTest.suite());
212 <        suite.addTest(ConcurrentSkipListSubMapTest.suite());
213 <        suite.addTest(ConcurrentSkipListSetTest.suite());
214 <        suite.addTest(ConcurrentSkipListSubSetTest.suite());
215 <        suite.addTest(CopyOnWriteArrayListTest.suite());
216 <        suite.addTest(CopyOnWriteArraySetTest.suite());
217 <        suite.addTest(CountDownLatchTest.suite());
218 <        suite.addTest(CyclicBarrierTest.suite());
219 <        suite.addTest(DelayQueueTest.suite());
220 <        suite.addTest(EntryTest.suite());
221 <        suite.addTest(ExchangerTest.suite());
222 <        suite.addTest(ExecutorsTest.suite());
223 <        suite.addTest(ExecutorCompletionServiceTest.suite());
224 <        suite.addTest(FutureTaskTest.suite());
225 <        suite.addTest(LinkedBlockingDequeTest.suite());
226 <        suite.addTest(LinkedBlockingQueueTest.suite());
227 <        suite.addTest(LinkedListTest.suite());
228 <        suite.addTest(LockSupportTest.suite());
229 <        suite.addTest(PriorityBlockingQueueTest.suite());
230 <        suite.addTest(PriorityQueueTest.suite());
231 <        suite.addTest(ReentrantLockTest.suite());
232 <        suite.addTest(ReentrantReadWriteLockTest.suite());
233 <        suite.addTest(ScheduledExecutorTest.suite());
234 <        suite.addTest(ScheduledExecutorSubclassTest.suite());
235 <        suite.addTest(SemaphoreTest.suite());
236 <        suite.addTest(SynchronousQueueTest.suite());
237 <        suite.addTest(SystemTest.suite());
238 <        suite.addTest(ThreadLocalTest.suite());
239 <        suite.addTest(ThreadPoolExecutorTest.suite());
240 <        suite.addTest(ThreadPoolExecutorSubclassTest.suite());
241 <        suite.addTest(ThreadTest.suite());
242 <        suite.addTest(TimeUnitTest.suite());
243 <        suite.addTest(TreeMapTest.suite());
244 <        suite.addTest(TreeSetTest.suite());
245 <        suite.addTest(TreeSubMapTest.suite());
188 <        suite.addTest(TreeSubSetTest.suite());
189 <
190 <        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 260 | public class JSR166TestCase extends Test
260          return 50;
261      }
262  
208
263      /**
264       * Sets delays as multiples of SHORT_DELAY.
265       */
# Line 213 | Line 267 | public class JSR166TestCase extends Test
267          SHORT_DELAY_MS = getShortDelay();
268          SMALL_DELAY_MS  = SHORT_DELAY_MS * 5;
269          MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
270 <        LONG_DELAY_MS   = SHORT_DELAY_MS * 50;
270 >        LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
271 >    }
272 >
273 >    /**
274 >     * Returns a timeout in milliseconds to be used in tests that
275 >     * verify that operations block or time out.
276 >     */
277 >    long timeoutMillis() {
278 >        return SHORT_DELAY_MS / 4;
279 >    }
280 >
281 >    /**
282 >     * Returns a new Date instance representing a time delayMillis
283 >     * milliseconds in the future.
284 >     */
285 >    Date delayedDate(long delayMillis) {
286 >        return new Date(System.currentTimeMillis() + delayMillis);
287      }
288  
289      /**
# Line 237 | Line 307 | public class JSR166TestCase extends Test
307      }
308  
309      /**
310 +     * Extra checks that get done for all test cases.
311 +     *
312       * Triggers test case failure if any thread assertions have failed,
313       * by rethrowing, in the test harness thread, any exception recorded
314       * earlier by threadRecordFailure.
315 +     *
316 +     * Triggers test case failure if interrupt status is set in the main thread.
317       */
318      public void tearDown() throws Exception {
319 <        Throwable t = threadFailure.get();
319 >        Throwable t = threadFailure.getAndSet(null);
320          if (t != null) {
321              if (t instanceof Error)
322                  throw (Error) t;
# Line 257 | Line 331 | public class JSR166TestCase extends Test
331                  throw afe;
332              }
333          }
334 +
335 +        if (Thread.interrupted())
336 +            throw new AssertionFailedError("interrupt status set in main thread");
337      }
338  
339      /**
# Line 388 | Line 465 | public class JSR166TestCase extends Test
465          else {
466              AssertionFailedError afe =
467                  new AssertionFailedError("unexpected exception: " + t);
468 <            t.initCause(t);
468 >            afe.initCause(t);
469              throw afe;
470          }
471      }
472  
473      /**
474 +     * Delays, via Thread.sleep, for the given millisecond delay, but
475 +     * if the sleep is shorter than specified, may re-sleep or yield
476 +     * until time elapses.
477 +     */
478 +    static void delay(long millis) throws InterruptedException {
479 +        long startTime = System.nanoTime();
480 +        long ns = millis * 1000 * 1000;
481 +        for (;;) {
482 +            if (millis > 0L)
483 +                Thread.sleep(millis);
484 +            else // too short to sleep
485 +                Thread.yield();
486 +            long d = ns - (System.nanoTime() - startTime);
487 +            if (d > 0L)
488 +                millis = d / (1000 * 1000);
489 +            else
490 +                break;
491 +        }
492 +    }
493 +
494 +    /**
495       * Waits out termination of a thread pool or fails doing so.
496       */
497 <    public void joinPool(ExecutorService exec) {
497 >    void joinPool(ExecutorService exec) {
498          try {
499              exec.shutdown();
500              assertTrue("ExecutorService did not terminate in a timely manner",
501 <                       exec.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
501 >                       exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS));
502          } catch (SecurityException ok) {
503              // Allowed in case test doesn't have privs
504          } catch (InterruptedException ie) {
# Line 408 | Line 506 | public class JSR166TestCase extends Test
506          }
507      }
508  
509 +    /**
510 +     * Checks that thread does not terminate within the default
511 +     * millisecond delay of {@code timeoutMillis()}.
512 +     */
513 +    void assertThreadStaysAlive(Thread thread) {
514 +        assertThreadStaysAlive(thread, timeoutMillis());
515 +    }
516 +
517 +    /**
518 +     * Checks that thread does not terminate within the given millisecond delay.
519 +     */
520 +    void assertThreadStaysAlive(Thread thread, long millis) {
521 +        try {
522 +            // No need to optimize the failing case via Thread.join.
523 +            delay(millis);
524 +            assertTrue(thread.isAlive());
525 +        } catch (InterruptedException ie) {
526 +            fail("Unexpected InterruptedException");
527 +        }
528 +    }
529 +
530 +    /**
531 +     * Checks that future.get times out, with the default timeout of
532 +     * {@code timeoutMillis()}.
533 +     */
534 +    void assertFutureTimesOut(Future future) {
535 +        assertFutureTimesOut(future, timeoutMillis());
536 +    }
537 +
538 +    /**
539 +     * Checks that future.get times out, with the given millisecond timeout.
540 +     */
541 +    void assertFutureTimesOut(Future future, long timeoutMillis) {
542 +        long startTime = System.nanoTime();
543 +        try {
544 +            future.get(timeoutMillis, MILLISECONDS);
545 +            shouldThrow();
546 +        } catch (TimeoutException success) {
547 +        } catch (Exception e) {
548 +            threadUnexpectedException(e);
549 +        } finally { future.cancel(true); }
550 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
551 +    }
552  
553      /**
554       * Fails with message "should throw exception".
# Line 534 | Line 675 | public class JSR166TestCase extends Test
675      }
676  
677      /**
678 <     * Sleep until the timeout has elapsed, or interrupted.
679 <     * Does <em>NOT</em> throw InterruptedException.
678 >     * Sleeps until the given time has elapsed.
679 >     * Throws AssertionFailedError if interrupted.
680       */
681 <    void sleepTillInterrupted(long timeoutMillis) {
681 >    void sleep(long millis) {
682          try {
683 <            Thread.sleep(timeoutMillis);
684 <        } catch (InterruptedException wakeup) {}
683 >            delay(millis);
684 >        } catch (InterruptedException ie) {
685 >            AssertionFailedError afe =
686 >                new AssertionFailedError("Unexpected InterruptedException");
687 >            afe.initCause(ie);
688 >            throw afe;
689 >        }
690 >    }
691 >
692 >    /**
693 >     * Spin-waits up to the specified number of milliseconds for the given
694 >     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
695 >     */
696 >    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
697 >        long startTime = System.nanoTime();
698 >        for (;;) {
699 >            Thread.State s = thread.getState();
700 >            if (s == Thread.State.BLOCKED ||
701 >                s == Thread.State.WAITING ||
702 >                s == Thread.State.TIMED_WAITING)
703 >                return;
704 >            else if (s == Thread.State.TERMINATED)
705 >                fail("Unexpected thread termination");
706 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
707 >                threadAssertTrue(thread.isAlive());
708 >                return;
709 >            }
710 >            Thread.yield();
711 >        }
712 >    }
713 >
714 >    /**
715 >     * Waits up to LONG_DELAY_MS for the given thread to enter a wait
716 >     * state: BLOCKED, WAITING, or TIMED_WAITING.
717 >     */
718 >    void waitForThreadToEnterWaitState(Thread thread) {
719 >        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
720 >    }
721 >
722 >    /**
723 >     * Returns the number of milliseconds since time given by
724 >     * startNanoTime, which must have been previously returned from a
725 >     * call to {@link System.nanoTime()}.
726 >     */
727 >    long millisElapsedSince(long startNanoTime) {
728 >        return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
729      }
730  
731      /**
732 <     * Returns a new started Thread running the given runnable.
732 >     * Returns a new started daemon Thread running the given runnable.
733       */
734      Thread newStartedThread(Runnable runnable) {
735          Thread t = new Thread(runnable);
736 +        t.setDaemon(true);
737          t.start();
738          return t;
739      }
740  
741 +    /**
742 +     * Waits for the specified time (in milliseconds) for the thread
743 +     * to terminate (using {@link Thread#join(long)}), else interrupts
744 +     * the thread (in the hope that it may terminate later) and fails.
745 +     */
746 +    void awaitTermination(Thread t, long timeoutMillis) {
747 +        try {
748 +            t.join(timeoutMillis);
749 +        } catch (InterruptedException ie) {
750 +            threadUnexpectedException(ie);
751 +        } finally {
752 +            if (t.getState() != Thread.State.TERMINATED) {
753 +                t.interrupt();
754 +                fail("Test timed out");
755 +            }
756 +        }
757 +    }
758 +
759 +    /**
760 +     * Waits for LONG_DELAY_MS milliseconds for the thread to
761 +     * terminate (using {@link Thread#join(long)}), else interrupts
762 +     * the thread (in the hope that it may terminate later) and fails.
763 +     */
764 +    void awaitTermination(Thread t) {
765 +        awaitTermination(t, LONG_DELAY_MS);
766 +    }
767 +
768      // Some convenient Runnable classes
769  
770      public abstract class CheckedRunnable implements Runnable {
# Line 614 | Line 827 | public class JSR166TestCase extends Test
827                  realRun();
828                  threadShouldThrow("InterruptedException");
829              } catch (InterruptedException success) {
830 +                threadAssertFalse(Thread.interrupted());
831              } catch (Throwable t) {
832                  threadUnexpectedException(t);
833              }
# Line 643 | Line 857 | public class JSR166TestCase extends Test
857                  threadShouldThrow("InterruptedException");
858                  return result;
859              } catch (InterruptedException success) {
860 +                threadAssertFalse(Thread.interrupted());
861              } catch (Throwable t) {
862                  threadUnexpectedException(t);
863              }
# Line 666 | Line 881 | public class JSR166TestCase extends Test
881  
882      public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
883          return new CheckedCallable<String>() {
884 <            public String realCall() {
884 >            protected String realCall() {
885                  try {
886                      latch.await();
887                  } catch (InterruptedException quittingTime) {}
# Line 674 | Line 889 | public class JSR166TestCase extends Test
889              }};
890      }
891  
892 +    public Runnable awaiter(final CountDownLatch latch) {
893 +        return new CheckedRunnable() {
894 +            public void realRun() throws InterruptedException {
895 +                await(latch);
896 +            }};
897 +    }
898 +
899 +    public void await(CountDownLatch latch) {
900 +        try {
901 +            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
902 +        } catch (Throwable t) {
903 +            threadUnexpectedException(t);
904 +        }
905 +    }
906 +
907 +    public void await(Semaphore semaphore) {
908 +        try {
909 +            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
910 +        } catch (Throwable t) {
911 +            threadUnexpectedException(t);
912 +        }
913 +    }
914 +
915 + //     /**
916 + //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
917 + //      */
918 + //     public void await(AtomicBoolean flag) {
919 + //         await(flag, LONG_DELAY_MS);
920 + //     }
921 +
922 + //     /**
923 + //      * Spin-waits up to the specified timeout until flag becomes true.
924 + //      */
925 + //     public void await(AtomicBoolean flag, long timeoutMillis) {
926 + //         long startTime = System.nanoTime();
927 + //         while (!flag.get()) {
928 + //             if (millisElapsedSince(startTime) > timeoutMillis)
929 + //                 throw new AssertionFailedError("timed out");
930 + //             Thread.yield();
931 + //         }
932 + //     }
933 +
934      public static class NPETask implements Callable<String> {
935          public String call() { throw new NullPointerException(); }
936      }
# Line 684 | Line 941 | public class JSR166TestCase extends Test
941  
942      public class ShortRunnable extends CheckedRunnable {
943          protected void realRun() throws Throwable {
944 <            Thread.sleep(SHORT_DELAY_MS);
944 >            delay(SHORT_DELAY_MS);
945          }
946      }
947  
948      public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
949          protected void realRun() throws InterruptedException {
950 <            Thread.sleep(SHORT_DELAY_MS);
950 >            delay(SHORT_DELAY_MS);
951          }
952      }
953  
954      public class SmallRunnable extends CheckedRunnable {
955          protected void realRun() throws Throwable {
956 <            Thread.sleep(SMALL_DELAY_MS);
956 >            delay(SMALL_DELAY_MS);
957          }
958      }
959  
960      public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
961          protected void realRun() {
962              try {
963 <                Thread.sleep(SMALL_DELAY_MS);
963 >                delay(SMALL_DELAY_MS);
964              } catch (InterruptedException ok) {}
965          }
966      }
967  
968      public class SmallCallable extends CheckedCallable {
969          protected Object realCall() throws InterruptedException {
970 <            Thread.sleep(SMALL_DELAY_MS);
970 >            delay(SMALL_DELAY_MS);
971              return Boolean.TRUE;
972          }
973      }
974  
975      public class MediumRunnable extends CheckedRunnable {
976          protected void realRun() throws Throwable {
977 <            Thread.sleep(MEDIUM_DELAY_MS);
977 >            delay(MEDIUM_DELAY_MS);
978          }
979      }
980  
981      public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
982          protected void realRun() throws InterruptedException {
983 <            Thread.sleep(MEDIUM_DELAY_MS);
983 >            delay(MEDIUM_DELAY_MS);
984          }
985      }
986  
987 +    public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
988 +        return new CheckedRunnable() {
989 +            protected void realRun() {
990 +                try {
991 +                    delay(timeoutMillis);
992 +                } catch (InterruptedException ok) {}
993 +            }};
994 +    }
995 +
996      public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
997          protected void realRun() {
998              try {
999 <                Thread.sleep(MEDIUM_DELAY_MS);
999 >                delay(MEDIUM_DELAY_MS);
1000              } catch (InterruptedException ok) {}
1001          }
1002      }
# Line 738 | Line 1004 | public class JSR166TestCase extends Test
1004      public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1005          protected void realRun() {
1006              try {
1007 <                Thread.sleep(LONG_DELAY_MS);
1007 >                delay(LONG_DELAY_MS);
1008              } catch (InterruptedException ok) {}
1009          }
1010      }
# Line 752 | Line 1018 | public class JSR166TestCase extends Test
1018          }
1019      }
1020  
1021 +    public interface TrackedRunnable extends Runnable {
1022 +        boolean isDone();
1023 +    }
1024 +
1025 +    public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
1026 +        return new TrackedRunnable() {
1027 +                private volatile boolean done = false;
1028 +                public boolean isDone() { return done; }
1029 +                public void run() {
1030 +                    try {
1031 +                        delay(timeoutMillis);
1032 +                        done = true;
1033 +                    } catch (InterruptedException ok) {}
1034 +                }
1035 +            };
1036 +    }
1037 +
1038      public static class TrackedShortRunnable implements Runnable {
1039          public volatile boolean done = false;
1040          public void run() {
1041              try {
1042 <                Thread.sleep(SMALL_DELAY_MS);
1042 >                delay(SHORT_DELAY_MS);
1043 >                done = true;
1044 >            } catch (InterruptedException ok) {}
1045 >        }
1046 >    }
1047 >
1048 >    public static class TrackedSmallRunnable implements Runnable {
1049 >        public volatile boolean done = false;
1050 >        public void run() {
1051 >            try {
1052 >                delay(SMALL_DELAY_MS);
1053                  done = true;
1054              } catch (InterruptedException ok) {}
1055          }
# Line 766 | Line 1059 | public class JSR166TestCase extends Test
1059          public volatile boolean done = false;
1060          public void run() {
1061              try {
1062 <                Thread.sleep(MEDIUM_DELAY_MS);
1062 >                delay(MEDIUM_DELAY_MS);
1063                  done = true;
1064              } catch (InterruptedException ok) {}
1065          }
# Line 776 | Line 1069 | public class JSR166TestCase extends Test
1069          public volatile boolean done = false;
1070          public void run() {
1071              try {
1072 <                Thread.sleep(LONG_DELAY_MS);
1072 >                delay(LONG_DELAY_MS);
1073                  done = true;
1074              } catch (InterruptedException ok) {}
1075          }
# Line 793 | Line 1086 | public class JSR166TestCase extends Test
1086          public volatile boolean done = false;
1087          public Object call() {
1088              try {
1089 <                Thread.sleep(SMALL_DELAY_MS);
1089 >                delay(SMALL_DELAY_MS);
1090                  done = true;
1091              } catch (InterruptedException ok) {}
1092              return Boolean.TRUE;
# Line 839 | Line 1132 | public class JSR166TestCase extends Test
1132                                        ThreadPoolExecutor executor) {}
1133      }
1134  
1135 +    /**
1136 +     * A CyclicBarrier that uses timed await and fails with
1137 +     * AssertionFailedErrors instead of throwing checked exceptions.
1138 +     */
1139 +    public class CheckedBarrier extends CyclicBarrier {
1140 +        public CheckedBarrier(int parties) { super(parties); }
1141 +
1142 +        public int await() {
1143 +            try {
1144 +                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1145 +            } catch (TimeoutException e) {
1146 +                throw new AssertionFailedError("timed out");
1147 +            } catch (Exception e) {
1148 +                AssertionFailedError afe =
1149 +                    new AssertionFailedError("Unexpected exception: " + e);
1150 +                afe.initCause(e);
1151 +                throw afe;
1152 +            }
1153 +        }
1154 +    }
1155 +
1156 +    void checkEmpty(BlockingQueue q) {
1157 +        try {
1158 +            assertTrue(q.isEmpty());
1159 +            assertEquals(0, q.size());
1160 +            assertNull(q.peek());
1161 +            assertNull(q.poll());
1162 +            assertNull(q.poll(0, MILLISECONDS));
1163 +            assertEquals(q.toString(), "[]");
1164 +            assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1165 +            assertFalse(q.iterator().hasNext());
1166 +            try {
1167 +                q.element();
1168 +                shouldThrow();
1169 +            } catch (NoSuchElementException success) {}
1170 +            try {
1171 +                q.iterator().next();
1172 +                shouldThrow();
1173 +            } catch (NoSuchElementException success) {}
1174 +            try {
1175 +                q.remove();
1176 +                shouldThrow();
1177 +            } catch (NoSuchElementException success) {}
1178 +        } catch (InterruptedException ie) {
1179 +            threadUnexpectedException(ie);
1180 +        }
1181 +    }
1182 +
1183 +    @SuppressWarnings("unchecked")
1184 +    <T> T serialClone(T o) {
1185 +        try {
1186 +            ByteArrayOutputStream bos = new ByteArrayOutputStream();
1187 +            ObjectOutputStream oos = new ObjectOutputStream(bos);
1188 +            oos.writeObject(o);
1189 +            oos.flush();
1190 +            oos.close();
1191 +            ObjectInputStream ois = new ObjectInputStream
1192 +                (new ByteArrayInputStream(bos.toByteArray()));
1193 +            T clone = (T) ois.readObject();
1194 +            assertSame(o.getClass(), clone.getClass());
1195 +            return clone;
1196 +        } catch (Throwable t) {
1197 +            threadUnexpectedException(t);
1198 +            return null;
1199 +        }
1200 +    }
1201   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines