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.59 by jsr166, Wed Oct 6 02:58:04 2010 UTC vs.
Revision 1.96 by jsr166, Mon Jan 21 19:51:46 2013 UTC

# Line 1 | Line 1
1   /*
2   * Written by Doug Lea with assistance from members of JCP JSR-166
3   * Expert Group and released to the public domain, as explained at
4 < * http://creativecommons.org/licenses/publicdomain
4 > * http://creativecommons.org/publicdomain/zero/1.0/
5   * Other contributors include Andrew Wright, Jeffrey Hayes,
6   * Pat Fisher, Mike Judd.
7   */
8  
9   import junit.framework.*;
10 + import java.io.ByteArrayInputStream;
11 + import java.io.ByteArrayOutputStream;
12 + import java.io.ObjectInputStream;
13 + import java.io.ObjectOutputStream;
14 + import java.lang.management.ManagementFactory;
15 + import java.lang.management.ThreadInfo;
16 + import java.util.ArrayList;
17 + import java.util.Arrays;
18 + import java.util.Date;
19 + import java.util.Enumeration;
20 + import java.util.List;
21 + import java.util.NoSuchElementException;
22   import java.util.PropertyPermission;
23   import java.util.concurrent.*;
24 + import java.util.concurrent.atomic.AtomicBoolean;
25   import java.util.concurrent.atomic.AtomicReference;
26   import static java.util.concurrent.TimeUnit.MILLISECONDS;
27 + import static java.util.concurrent.TimeUnit.NANOSECONDS;
28   import java.security.CodeSource;
29   import java.security.Permission;
30   import java.security.PermissionCollection;
# Line 60 | Line 74 | import java.security.SecurityPermission;
74   *
75   * </ol>
76   *
77 < * <p> <b>Other notes</b>
77 > * <p><b>Other notes</b>
78   * <ul>
79   *
80   * <li> Usually, there is one testcase method per JSR166 method
# Line 96 | Line 110 | public class JSR166TestCase extends Test
110      private static final boolean useSecurityManager =
111          Boolean.getBoolean("jsr166.useSecurityManager");
112  
113 +    protected static final boolean expensiveTests =
114 +        Boolean.getBoolean("jsr166.expensiveTests");
115 +
116 +    /**
117 +     * If true, report on stdout all "slow" tests, that is, ones that
118 +     * take more than profileThreshold milliseconds to execute.
119 +     */
120 +    private static final boolean profileTests =
121 +        Boolean.getBoolean("jsr166.profileTests");
122 +
123 +    /**
124 +     * The number of milliseconds that tests are permitted for
125 +     * execution without being reported, when profileTests is set.
126 +     */
127 +    private static final long profileThreshold =
128 +        Long.getLong("jsr166.profileThreshold", 100);
129 +
130 +    protected void runTest() throws Throwable {
131 +        if (profileTests)
132 +            runTestProfiled();
133 +        else
134 +            super.runTest();
135 +    }
136 +
137 +    protected void runTestProfiled() throws Throwable {
138 +        long t0 = System.nanoTime();
139 +        try {
140 +            super.runTest();
141 +        } finally {
142 +            long elapsedMillis =
143 +                (System.nanoTime() - t0) / (1000L * 1000L);
144 +            if (elapsedMillis >= profileThreshold)
145 +                System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
146 +        }
147 +    }
148 +
149      /**
150 <     * Runs all JSR166 unit tests using junit.textui.TestRunner
150 >     * Runs all JSR166 unit tests using junit.textui.TestRunner.
151 >     * Optional command line arg provides the number of iterations to
152 >     * repeat running the tests.
153       */
154      public static void main(String[] args) {
155          if (useSecurityManager) {
# Line 116 | Line 168 | public class JSR166TestCase extends Test
168          System.exit(0);
169      }
170  
171 +    public static TestSuite newTestSuite(Object... suiteOrClasses) {
172 +        TestSuite suite = new TestSuite();
173 +        for (Object suiteOrClass : suiteOrClasses) {
174 +            if (suiteOrClass instanceof TestSuite)
175 +                suite.addTest((TestSuite) suiteOrClass);
176 +            else if (suiteOrClass instanceof Class)
177 +                suite.addTest(new TestSuite((Class<?>) suiteOrClass));
178 +            else
179 +                throw new ClassCastException("not a test suite or class");
180 +        }
181 +        return suite;
182 +    }
183 +
184      /**
185 <     * Collects all JSR166 unit tests as one suite
185 >     * Collects all JSR166 unit tests as one suite.
186       */
187      public static Test suite() {
188 <        TestSuite suite = new TestSuite("JSR166 Unit Tests");
189 <
190 <        suite.addTest(ForkJoinPoolTest.suite());
191 <        suite.addTest(ForkJoinTaskTest.suite());
192 <        suite.addTest(RecursiveActionTest.suite());
193 <        suite.addTest(RecursiveTaskTest.suite());
194 <        suite.addTest(LinkedTransferQueueTest.suite());
195 <        suite.addTest(PhaserTest.suite());
196 <        suite.addTest(ThreadLocalRandomTest.suite());
197 <        suite.addTest(AbstractExecutorServiceTest.suite());
198 <        suite.addTest(AbstractQueueTest.suite());
199 <        suite.addTest(AbstractQueuedSynchronizerTest.suite());
200 <        suite.addTest(AbstractQueuedLongSynchronizerTest.suite());
201 <        suite.addTest(ArrayBlockingQueueTest.suite());
202 <        suite.addTest(ArrayDequeTest.suite());
203 <        suite.addTest(AtomicBooleanTest.suite());
204 <        suite.addTest(AtomicIntegerArrayTest.suite());
205 <        suite.addTest(AtomicIntegerFieldUpdaterTest.suite());
206 <        suite.addTest(AtomicIntegerTest.suite());
207 <        suite.addTest(AtomicLongArrayTest.suite());
208 <        suite.addTest(AtomicLongFieldUpdaterTest.suite());
209 <        suite.addTest(AtomicLongTest.suite());
210 <        suite.addTest(AtomicMarkableReferenceTest.suite());
211 <        suite.addTest(AtomicReferenceArrayTest.suite());
212 <        suite.addTest(AtomicReferenceFieldUpdaterTest.suite());
213 <        suite.addTest(AtomicReferenceTest.suite());
214 <        suite.addTest(AtomicStampedReferenceTest.suite());
215 <        suite.addTest(ConcurrentHashMapTest.suite());
216 <        suite.addTest(ConcurrentLinkedDequeTest.suite());
217 <        suite.addTest(ConcurrentLinkedQueueTest.suite());
218 <        suite.addTest(ConcurrentSkipListMapTest.suite());
219 <        suite.addTest(ConcurrentSkipListSubMapTest.suite());
220 <        suite.addTest(ConcurrentSkipListSetTest.suite());
221 <        suite.addTest(ConcurrentSkipListSubSetTest.suite());
222 <        suite.addTest(CopyOnWriteArrayListTest.suite());
223 <        suite.addTest(CopyOnWriteArraySetTest.suite());
224 <        suite.addTest(CountDownLatchTest.suite());
225 <        suite.addTest(CyclicBarrierTest.suite());
226 <        suite.addTest(DelayQueueTest.suite());
227 <        suite.addTest(EntryTest.suite());
228 <        suite.addTest(ExchangerTest.suite());
229 <        suite.addTest(ExecutorsTest.suite());
230 <        suite.addTest(ExecutorCompletionServiceTest.suite());
231 <        suite.addTest(FutureTaskTest.suite());
232 <        suite.addTest(LinkedBlockingDequeTest.suite());
233 <        suite.addTest(LinkedBlockingQueueTest.suite());
234 <        suite.addTest(LinkedListTest.suite());
235 <        suite.addTest(LockSupportTest.suite());
236 <        suite.addTest(PriorityBlockingQueueTest.suite());
237 <        suite.addTest(PriorityQueueTest.suite());
238 <        suite.addTest(ReentrantLockTest.suite());
239 <        suite.addTest(ReentrantReadWriteLockTest.suite());
240 <        suite.addTest(ScheduledExecutorTest.suite());
241 <        suite.addTest(ScheduledExecutorSubclassTest.suite());
242 <        suite.addTest(SemaphoreTest.suite());
243 <        suite.addTest(SynchronousQueueTest.suite());
244 <        suite.addTest(SystemTest.suite());
245 <        suite.addTest(ThreadLocalTest.suite());
246 <        suite.addTest(ThreadPoolExecutorTest.suite());
247 <        suite.addTest(ThreadPoolExecutorSubclassTest.suite());
248 <        suite.addTest(ThreadTest.suite());
249 <        suite.addTest(TimeUnitTest.suite());
250 <        suite.addTest(TreeMapTest.suite());
251 <        suite.addTest(TreeSetTest.suite());
252 <        suite.addTest(TreeSubMapTest.suite());
188 <        suite.addTest(TreeSubSetTest.suite());
189 <
190 <        return suite;
188 >        return newTestSuite(
189 >            ForkJoinPoolTest.suite(),
190 >            ForkJoinTaskTest.suite(),
191 >            RecursiveActionTest.suite(),
192 >            RecursiveTaskTest.suite(),
193 >            LinkedTransferQueueTest.suite(),
194 >            PhaserTest.suite(),
195 >            ThreadLocalRandomTest.suite(),
196 >            AbstractExecutorServiceTest.suite(),
197 >            AbstractQueueTest.suite(),
198 >            AbstractQueuedSynchronizerTest.suite(),
199 >            AbstractQueuedLongSynchronizerTest.suite(),
200 >            ArrayBlockingQueueTest.suite(),
201 >            ArrayDequeTest.suite(),
202 >            AtomicBooleanTest.suite(),
203 >            AtomicIntegerArrayTest.suite(),
204 >            AtomicIntegerFieldUpdaterTest.suite(),
205 >            AtomicIntegerTest.suite(),
206 >            AtomicLongArrayTest.suite(),
207 >            AtomicLongFieldUpdaterTest.suite(),
208 >            AtomicLongTest.suite(),
209 >            AtomicMarkableReferenceTest.suite(),
210 >            AtomicReferenceArrayTest.suite(),
211 >            AtomicReferenceFieldUpdaterTest.suite(),
212 >            AtomicReferenceTest.suite(),
213 >            AtomicStampedReferenceTest.suite(),
214 >            ConcurrentHashMapTest.suite(),
215 >            ConcurrentLinkedDequeTest.suite(),
216 >            ConcurrentLinkedQueueTest.suite(),
217 >            ConcurrentSkipListMapTest.suite(),
218 >            ConcurrentSkipListSubMapTest.suite(),
219 >            ConcurrentSkipListSetTest.suite(),
220 >            ConcurrentSkipListSubSetTest.suite(),
221 >            CopyOnWriteArrayListTest.suite(),
222 >            CopyOnWriteArraySetTest.suite(),
223 >            CountDownLatchTest.suite(),
224 >            CyclicBarrierTest.suite(),
225 >            DelayQueueTest.suite(),
226 >            EntryTest.suite(),
227 >            ExchangerTest.suite(),
228 >            ExecutorsTest.suite(),
229 >            ExecutorCompletionServiceTest.suite(),
230 >            FutureTaskTest.suite(),
231 >            LinkedBlockingDequeTest.suite(),
232 >            LinkedBlockingQueueTest.suite(),
233 >            LinkedListTest.suite(),
234 >            LockSupportTest.suite(),
235 >            PriorityBlockingQueueTest.suite(),
236 >            PriorityQueueTest.suite(),
237 >            ReentrantLockTest.suite(),
238 >            ReentrantReadWriteLockTest.suite(),
239 >            ScheduledExecutorTest.suite(),
240 >            ScheduledExecutorSubclassTest.suite(),
241 >            SemaphoreTest.suite(),
242 >            SynchronousQueueTest.suite(),
243 >            SystemTest.suite(),
244 >            ThreadLocalTest.suite(),
245 >            ThreadPoolExecutorTest.suite(),
246 >            ThreadPoolExecutorSubclassTest.suite(),
247 >            ThreadTest.suite(),
248 >            TimeUnitTest.suite(),
249 >            TreeMapTest.suite(),
250 >            TreeSetTest.suite(),
251 >            TreeSubMapTest.suite(),
252 >            TreeSubSetTest.suite());
253      }
254  
255  
# Line 205 | Line 267 | public class JSR166TestCase extends Test
267          return 50;
268      }
269  
208
270      /**
271       * Sets delays as multiples of SHORT_DELAY.
272       */
# Line 213 | Line 274 | public class JSR166TestCase extends Test
274          SHORT_DELAY_MS = getShortDelay();
275          SMALL_DELAY_MS  = SHORT_DELAY_MS * 5;
276          MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
277 <        LONG_DELAY_MS   = SHORT_DELAY_MS * 50;
277 >        LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
278 >    }
279 >
280 >    /**
281 >     * Returns a timeout in milliseconds to be used in tests that
282 >     * verify that operations block or time out.
283 >     */
284 >    long timeoutMillis() {
285 >        return SHORT_DELAY_MS / 4;
286 >    }
287 >
288 >    /**
289 >     * Returns a new Date instance representing a time delayMillis
290 >     * milliseconds in the future.
291 >     */
292 >    Date delayedDate(long delayMillis) {
293 >        return new Date(System.currentTimeMillis() + delayMillis);
294      }
295  
296      /**
# Line 237 | Line 314 | public class JSR166TestCase extends Test
314      }
315  
316      /**
317 +     * Extra checks that get done for all test cases.
318 +     *
319       * Triggers test case failure if any thread assertions have failed,
320       * by rethrowing, in the test harness thread, any exception recorded
321       * earlier by threadRecordFailure.
322 +     *
323 +     * Triggers test case failure if interrupt status is set in the main thread.
324       */
325      public void tearDown() throws Exception {
326 <        Throwable t = threadFailure.get();
326 >        Throwable t = threadFailure.getAndSet(null);
327          if (t != null) {
328              if (t instanceof Error)
329                  throw (Error) t;
# Line 257 | Line 338 | public class JSR166TestCase extends Test
338                  throw afe;
339              }
340          }
341 +
342 +        if (Thread.interrupted())
343 +            throw new AssertionFailedError("interrupt status set in main thread");
344      }
345  
346      /**
# Line 388 | Line 472 | public class JSR166TestCase extends Test
472          else {
473              AssertionFailedError afe =
474                  new AssertionFailedError("unexpected exception: " + t);
475 <            t.initCause(t);
475 >            afe.initCause(t);
476              throw afe;
477          }
478      }
479  
480      /**
481 +     * Delays, via Thread.sleep, for the given millisecond delay, but
482 +     * if the sleep is shorter than specified, may re-sleep or yield
483 +     * until time elapses.
484 +     */
485 +    static void delay(long millis) throws InterruptedException {
486 +        long startTime = System.nanoTime();
487 +        long ns = millis * 1000 * 1000;
488 +        for (;;) {
489 +            if (millis > 0L)
490 +                Thread.sleep(millis);
491 +            else // too short to sleep
492 +                Thread.yield();
493 +            long d = ns - (System.nanoTime() - startTime);
494 +            if (d > 0L)
495 +                millis = d / (1000 * 1000);
496 +            else
497 +                break;
498 +        }
499 +    }
500 +
501 +    /**
502       * Waits out termination of a thread pool or fails doing so.
503       */
504 <    public void joinPool(ExecutorService exec) {
504 >    void joinPool(ExecutorService exec) {
505          try {
506              exec.shutdown();
507              assertTrue("ExecutorService did not terminate in a timely manner",
508 <                       exec.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
508 >                       exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS));
509          } catch (SecurityException ok) {
510              // Allowed in case test doesn't have privs
511          } catch (InterruptedException ie) {
# Line 408 | Line 513 | public class JSR166TestCase extends Test
513          }
514      }
515  
516 +    /**
517 +     * A debugging tool to print all stack traces, as jstack does.
518 +     */
519 +    static void printAllStackTraces() {
520 +        for (ThreadInfo info :
521 +                 ManagementFactory.getThreadMXBean()
522 +                 .dumpAllThreads(true, true))
523 +            System.err.print(info);
524 +    }
525 +
526 +    /**
527 +     * Checks that thread does not terminate within the default
528 +     * millisecond delay of {@code timeoutMillis()}.
529 +     */
530 +    void assertThreadStaysAlive(Thread thread) {
531 +        assertThreadStaysAlive(thread, timeoutMillis());
532 +    }
533 +
534 +    /**
535 +     * Checks that thread does not terminate within the given millisecond delay.
536 +     */
537 +    void assertThreadStaysAlive(Thread thread, long millis) {
538 +        try {
539 +            // No need to optimize the failing case via Thread.join.
540 +            delay(millis);
541 +            assertTrue(thread.isAlive());
542 +        } catch (InterruptedException ie) {
543 +            fail("Unexpected InterruptedException");
544 +        }
545 +    }
546 +
547 +    /**
548 +     * Checks that the threads do not terminate within the default
549 +     * millisecond delay of {@code timeoutMillis()}.
550 +     */
551 +    void assertThreadsStayAlive(Thread... threads) {
552 +        assertThreadsStayAlive(timeoutMillis(), threads);
553 +    }
554 +
555 +    /**
556 +     * Checks that the threads do not terminate within the given millisecond delay.
557 +     */
558 +    void assertThreadsStayAlive(long millis, Thread... threads) {
559 +        try {
560 +            // No need to optimize the failing case via Thread.join.
561 +            delay(millis);
562 +            for (Thread thread : threads)
563 +                assertTrue(thread.isAlive());
564 +        } catch (InterruptedException ie) {
565 +            fail("Unexpected InterruptedException");
566 +        }
567 +    }
568 +
569 +    /**
570 +     * Checks that future.get times out, with the default timeout of
571 +     * {@code timeoutMillis()}.
572 +     */
573 +    void assertFutureTimesOut(Future future) {
574 +        assertFutureTimesOut(future, timeoutMillis());
575 +    }
576 +
577 +    /**
578 +     * Checks that future.get times out, with the given millisecond timeout.
579 +     */
580 +    void assertFutureTimesOut(Future future, long timeoutMillis) {
581 +        long startTime = System.nanoTime();
582 +        try {
583 +            future.get(timeoutMillis, MILLISECONDS);
584 +            shouldThrow();
585 +        } catch (TimeoutException success) {
586 +        } catch (Exception e) {
587 +            threadUnexpectedException(e);
588 +        } finally { future.cancel(true); }
589 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
590 +    }
591  
592      /**
593       * Fails with message "should throw exception".
# Line 460 | Line 640 | public class JSR166TestCase extends Test
640          SecurityManager sm = System.getSecurityManager();
641          if (sm == null) {
642              r.run();
643 +        }
644 +        runWithSecurityManagerWithPermissions(r, permissions);
645 +    }
646 +
647 +    /**
648 +     * Runs Runnable r with a security policy that permits precisely
649 +     * the specified permissions.  If there is no current security
650 +     * manager, a temporary one is set for the duration of the
651 +     * Runnable.  We require that any security manager permit
652 +     * getPolicy/setPolicy.
653 +     */
654 +    public void runWithSecurityManagerWithPermissions(Runnable r,
655 +                                                      Permission... permissions) {
656 +        SecurityManager sm = System.getSecurityManager();
657 +        if (sm == null) {
658              Policy savedPolicy = Policy.getPolicy();
659              try {
660                  Policy.setPolicy(permissivePolicy());
661                  System.setSecurityManager(new SecurityManager());
662 <                runWithPermissions(r, permissions);
662 >                runWithSecurityManagerWithPermissions(r, permissions);
663              } finally {
664                  System.setSecurityManager(null);
665                  Policy.setPolicy(savedPolicy);
# Line 512 | Line 707 | public class JSR166TestCase extends Test
707              return perms.implies(p);
708          }
709          public void refresh() {}
710 +        public String toString() {
711 +            List<Permission> ps = new ArrayList<Permission>();
712 +            for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
713 +                ps.add(e.nextElement());
714 +            return "AdjustablePolicy with permissions " + ps;
715 +        }
716      }
717  
718      /**
# Line 534 | Line 735 | public class JSR166TestCase extends Test
735      }
736  
737      /**
738 <     * Sleeps until the timeout has elapsed, or interrupted.
739 <     * Does <em>NOT</em> throw InterruptedException.
738 >     * Sleeps until the given time has elapsed.
739 >     * Throws AssertionFailedError if interrupted.
740       */
741 <    void sleepTillInterrupted(long timeoutMillis) {
741 >    void sleep(long millis) {
742          try {
743 <            Thread.sleep(timeoutMillis);
744 <        } catch (InterruptedException wakeup) {}
743 >            delay(millis);
744 >        } catch (InterruptedException ie) {
745 >            AssertionFailedError afe =
746 >                new AssertionFailedError("Unexpected InterruptedException");
747 >            afe.initCause(ie);
748 >            throw afe;
749 >        }
750 >    }
751 >
752 >    /**
753 >     * Spin-waits up to the specified number of milliseconds for the given
754 >     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
755 >     */
756 >    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
757 >        long startTime = System.nanoTime();
758 >        for (;;) {
759 >            Thread.State s = thread.getState();
760 >            if (s == Thread.State.BLOCKED ||
761 >                s == Thread.State.WAITING ||
762 >                s == Thread.State.TIMED_WAITING)
763 >                return;
764 >            else if (s == Thread.State.TERMINATED)
765 >                fail("Unexpected thread termination");
766 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
767 >                threadAssertTrue(thread.isAlive());
768 >                return;
769 >            }
770 >            Thread.yield();
771 >        }
772 >    }
773 >
774 >    /**
775 >     * Waits up to LONG_DELAY_MS for the given thread to enter a wait
776 >     * state: BLOCKED, WAITING, or TIMED_WAITING.
777 >     */
778 >    void waitForThreadToEnterWaitState(Thread thread) {
779 >        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
780 >    }
781 >
782 >    /**
783 >     * Returns the number of milliseconds since time given by
784 >     * startNanoTime, which must have been previously returned from a
785 >     * call to {@link System.nanoTime()}.
786 >     */
787 >    long millisElapsedSince(long startNanoTime) {
788 >        return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
789      }
790  
791      /**
# Line 564 | Line 809 | public class JSR166TestCase extends Test
809          } catch (InterruptedException ie) {
810              threadUnexpectedException(ie);
811          } finally {
812 <            if (t.isAlive()) {
812 >            if (t.getState() != Thread.State.TERMINATED) {
813                  t.interrupt();
814                  fail("Test timed out");
815              }
816          }
817      }
818  
819 +    /**
820 +     * Waits for LONG_DELAY_MS milliseconds for the thread to
821 +     * terminate (using {@link Thread#join(long)}), else interrupts
822 +     * the thread (in the hope that it may terminate later) and fails.
823 +     */
824 +    void awaitTermination(Thread t) {
825 +        awaitTermination(t, LONG_DELAY_MS);
826 +    }
827 +
828      // Some convenient Runnable classes
829  
830      public abstract class CheckedRunnable implements Runnable {
# Line 633 | Line 887 | public class JSR166TestCase extends Test
887                  realRun();
888                  threadShouldThrow("InterruptedException");
889              } catch (InterruptedException success) {
890 +                threadAssertFalse(Thread.interrupted());
891              } catch (Throwable t) {
892                  threadUnexpectedException(t);
893              }
# Line 662 | Line 917 | public class JSR166TestCase extends Test
917                  threadShouldThrow("InterruptedException");
918                  return result;
919              } catch (InterruptedException success) {
920 +                threadAssertFalse(Thread.interrupted());
921              } catch (Throwable t) {
922                  threadUnexpectedException(t);
923              }
# Line 685 | Line 941 | public class JSR166TestCase extends Test
941  
942      public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
943          return new CheckedCallable<String>() {
944 <            public String realCall() {
944 >            protected String realCall() {
945                  try {
946                      latch.await();
947                  } catch (InterruptedException quittingTime) {}
# Line 693 | Line 949 | public class JSR166TestCase extends Test
949              }};
950      }
951  
952 +    public Runnable awaiter(final CountDownLatch latch) {
953 +        return new CheckedRunnable() {
954 +            public void realRun() throws InterruptedException {
955 +                await(latch);
956 +            }};
957 +    }
958 +
959 +    public void await(CountDownLatch latch) {
960 +        try {
961 +            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
962 +        } catch (Throwable t) {
963 +            threadUnexpectedException(t);
964 +        }
965 +    }
966 +
967 +    public void await(Semaphore semaphore) {
968 +        try {
969 +            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
970 +        } catch (Throwable t) {
971 +            threadUnexpectedException(t);
972 +        }
973 +    }
974 +
975 + //     /**
976 + //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
977 + //      */
978 + //     public void await(AtomicBoolean flag) {
979 + //         await(flag, LONG_DELAY_MS);
980 + //     }
981 +
982 + //     /**
983 + //      * Spin-waits up to the specified timeout until flag becomes true.
984 + //      */
985 + //     public void await(AtomicBoolean flag, long timeoutMillis) {
986 + //         long startTime = System.nanoTime();
987 + //         while (!flag.get()) {
988 + //             if (millisElapsedSince(startTime) > timeoutMillis)
989 + //                 throw new AssertionFailedError("timed out");
990 + //             Thread.yield();
991 + //         }
992 + //     }
993 +
994      public static class NPETask implements Callable<String> {
995          public String call() { throw new NullPointerException(); }
996      }
# Line 703 | Line 1001 | public class JSR166TestCase extends Test
1001  
1002      public class ShortRunnable extends CheckedRunnable {
1003          protected void realRun() throws Throwable {
1004 <            Thread.sleep(SHORT_DELAY_MS);
1004 >            delay(SHORT_DELAY_MS);
1005          }
1006      }
1007  
1008      public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1009          protected void realRun() throws InterruptedException {
1010 <            Thread.sleep(SHORT_DELAY_MS);
1010 >            delay(SHORT_DELAY_MS);
1011          }
1012      }
1013  
1014      public class SmallRunnable extends CheckedRunnable {
1015          protected void realRun() throws Throwable {
1016 <            Thread.sleep(SMALL_DELAY_MS);
1016 >            delay(SMALL_DELAY_MS);
1017          }
1018      }
1019  
1020      public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1021          protected void realRun() {
1022              try {
1023 <                Thread.sleep(SMALL_DELAY_MS);
1023 >                delay(SMALL_DELAY_MS);
1024              } catch (InterruptedException ok) {}
1025          }
1026      }
1027  
1028      public class SmallCallable extends CheckedCallable {
1029          protected Object realCall() throws InterruptedException {
1030 <            Thread.sleep(SMALL_DELAY_MS);
1030 >            delay(SMALL_DELAY_MS);
1031              return Boolean.TRUE;
1032          }
1033      }
1034  
1035      public class MediumRunnable extends CheckedRunnable {
1036          protected void realRun() throws Throwable {
1037 <            Thread.sleep(MEDIUM_DELAY_MS);
1037 >            delay(MEDIUM_DELAY_MS);
1038          }
1039      }
1040  
1041      public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1042          protected void realRun() throws InterruptedException {
1043 <            Thread.sleep(MEDIUM_DELAY_MS);
1043 >            delay(MEDIUM_DELAY_MS);
1044          }
1045      }
1046  
1047 +    public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1048 +        return new CheckedRunnable() {
1049 +            protected void realRun() {
1050 +                try {
1051 +                    delay(timeoutMillis);
1052 +                } catch (InterruptedException ok) {}
1053 +            }};
1054 +    }
1055 +
1056      public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1057          protected void realRun() {
1058              try {
1059 <                Thread.sleep(MEDIUM_DELAY_MS);
1059 >                delay(MEDIUM_DELAY_MS);
1060              } catch (InterruptedException ok) {}
1061          }
1062      }
# Line 757 | Line 1064 | public class JSR166TestCase extends Test
1064      public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1065          protected void realRun() {
1066              try {
1067 <                Thread.sleep(LONG_DELAY_MS);
1067 >                delay(LONG_DELAY_MS);
1068              } catch (InterruptedException ok) {}
1069          }
1070      }
# Line 771 | Line 1078 | public class JSR166TestCase extends Test
1078          }
1079      }
1080  
1081 +    public interface TrackedRunnable extends Runnable {
1082 +        boolean isDone();
1083 +    }
1084 +
1085 +    public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
1086 +        return new TrackedRunnable() {
1087 +                private volatile boolean done = false;
1088 +                public boolean isDone() { return done; }
1089 +                public void run() {
1090 +                    try {
1091 +                        delay(timeoutMillis);
1092 +                        done = true;
1093 +                    } catch (InterruptedException ok) {}
1094 +                }
1095 +            };
1096 +    }
1097 +
1098      public static class TrackedShortRunnable implements Runnable {
1099          public volatile boolean done = false;
1100          public void run() {
1101              try {
1102 <                Thread.sleep(SMALL_DELAY_MS);
1102 >                delay(SHORT_DELAY_MS);
1103 >                done = true;
1104 >            } catch (InterruptedException ok) {}
1105 >        }
1106 >    }
1107 >
1108 >    public static class TrackedSmallRunnable implements Runnable {
1109 >        public volatile boolean done = false;
1110 >        public void run() {
1111 >            try {
1112 >                delay(SMALL_DELAY_MS);
1113                  done = true;
1114              } catch (InterruptedException ok) {}
1115          }
# Line 785 | Line 1119 | public class JSR166TestCase extends Test
1119          public volatile boolean done = false;
1120          public void run() {
1121              try {
1122 <                Thread.sleep(MEDIUM_DELAY_MS);
1122 >                delay(MEDIUM_DELAY_MS);
1123                  done = true;
1124              } catch (InterruptedException ok) {}
1125          }
# Line 795 | Line 1129 | public class JSR166TestCase extends Test
1129          public volatile boolean done = false;
1130          public void run() {
1131              try {
1132 <                Thread.sleep(LONG_DELAY_MS);
1132 >                delay(LONG_DELAY_MS);
1133                  done = true;
1134              } catch (InterruptedException ok) {}
1135          }
# Line 812 | Line 1146 | public class JSR166TestCase extends Test
1146          public volatile boolean done = false;
1147          public Object call() {
1148              try {
1149 <                Thread.sleep(SMALL_DELAY_MS);
1149 >                delay(SMALL_DELAY_MS);
1150                  done = true;
1151              } catch (InterruptedException ok) {}
1152              return Boolean.TRUE;
# Line 858 | Line 1192 | public class JSR166TestCase extends Test
1192                                        ThreadPoolExecutor executor) {}
1193      }
1194  
1195 +    /**
1196 +     * A CyclicBarrier that uses timed await and fails with
1197 +     * AssertionFailedErrors instead of throwing checked exceptions.
1198 +     */
1199 +    public class CheckedBarrier extends CyclicBarrier {
1200 +        public CheckedBarrier(int parties) { super(parties); }
1201 +
1202 +        public int await() {
1203 +            try {
1204 +                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1205 +            } catch (TimeoutException e) {
1206 +                throw new AssertionFailedError("timed out");
1207 +            } catch (Exception e) {
1208 +                AssertionFailedError afe =
1209 +                    new AssertionFailedError("Unexpected exception: " + e);
1210 +                afe.initCause(e);
1211 +                throw afe;
1212 +            }
1213 +        }
1214 +    }
1215 +
1216 +    void checkEmpty(BlockingQueue q) {
1217 +        try {
1218 +            assertTrue(q.isEmpty());
1219 +            assertEquals(0, q.size());
1220 +            assertNull(q.peek());
1221 +            assertNull(q.poll());
1222 +            assertNull(q.poll(0, MILLISECONDS));
1223 +            assertEquals(q.toString(), "[]");
1224 +            assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1225 +            assertFalse(q.iterator().hasNext());
1226 +            try {
1227 +                q.element();
1228 +                shouldThrow();
1229 +            } catch (NoSuchElementException success) {}
1230 +            try {
1231 +                q.iterator().next();
1232 +                shouldThrow();
1233 +            } catch (NoSuchElementException success) {}
1234 +            try {
1235 +                q.remove();
1236 +                shouldThrow();
1237 +            } catch (NoSuchElementException success) {}
1238 +        } catch (InterruptedException ie) {
1239 +            threadUnexpectedException(ie);
1240 +        }
1241 +    }
1242 +
1243 +    void assertSerialEquals(Object x, Object y) {
1244 +        assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1245 +    }
1246 +
1247 +    void assertNotSerialEquals(Object x, Object y) {
1248 +        assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1249 +    }
1250 +
1251 +    byte[] serialBytes(Object o) {
1252 +        try {
1253 +            ByteArrayOutputStream bos = new ByteArrayOutputStream();
1254 +            ObjectOutputStream oos = new ObjectOutputStream(bos);
1255 +            oos.writeObject(o);
1256 +            oos.flush();
1257 +            oos.close();
1258 +            return bos.toByteArray();
1259 +        } catch (Throwable t) {
1260 +            threadUnexpectedException(t);
1261 +            return new byte[0];
1262 +        }
1263 +    }
1264 +
1265 +    @SuppressWarnings("unchecked")
1266 +    <T> T serialClone(T o) {
1267 +        try {
1268 +            ObjectInputStream ois = new ObjectInputStream
1269 +                (new ByteArrayInputStream(serialBytes(o)));
1270 +            T clone = (T) ois.readObject();
1271 +            assertSame(o.getClass(), clone.getClass());
1272 +            return clone;
1273 +        } catch (Throwable t) {
1274 +            threadUnexpectedException(t);
1275 +            return null;
1276 +        }
1277 +    }
1278   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines