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.58 by jsr166, Wed Oct 6 02:11:57 2010 UTC vs.
Revision 1.102 by jsr166, Wed Feb 6 19:55:06 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.lang.reflect.Method;
17 + import java.util.ArrayList;
18 + import java.util.Arrays;
19 + import java.util.Date;
20 + import java.util.Enumeration;
21 + import java.util.List;
22 + import java.util.NoSuchElementException;
23   import java.util.PropertyPermission;
24   import java.util.concurrent.*;
25 + import java.util.concurrent.atomic.AtomicBoolean;
26   import java.util.concurrent.atomic.AtomicReference;
27   import static java.util.concurrent.TimeUnit.MILLISECONDS;
28 + import static java.util.concurrent.TimeUnit.NANOSECONDS;
29   import java.security.CodeSource;
30   import java.security.Permission;
31   import java.security.PermissionCollection;
# Line 60 | Line 75 | import java.security.SecurityPermission;
75   *
76   * </ol>
77   *
78 < * <p> <b>Other notes</b>
78 > * <p><b>Other notes</b>
79   * <ul>
80   *
81   * <li> Usually, there is one testcase method per JSR166 method
# Line 96 | Line 111 | public class JSR166TestCase extends Test
111      private static final boolean useSecurityManager =
112          Boolean.getBoolean("jsr166.useSecurityManager");
113  
114 +    protected static final boolean expensiveTests =
115 +        Boolean.getBoolean("jsr166.expensiveTests");
116 +
117 +    /**
118 +     * If true, report on stdout all "slow" tests, that is, ones that
119 +     * take more than profileThreshold milliseconds to execute.
120 +     */
121 +    private static final boolean profileTests =
122 +        Boolean.getBoolean("jsr166.profileTests");
123 +
124 +    /**
125 +     * The number of milliseconds that tests are permitted for
126 +     * execution without being reported, when profileTests is set.
127 +     */
128 +    private static final long profileThreshold =
129 +        Long.getLong("jsr166.profileThreshold", 100);
130 +
131 +    protected void runTest() throws Throwable {
132 +        if (profileTests)
133 +            runTestProfiled();
134 +        else
135 +            super.runTest();
136 +    }
137 +
138 +    protected void runTestProfiled() throws Throwable {
139 +        long t0 = System.nanoTime();
140 +        try {
141 +            super.runTest();
142 +        } finally {
143 +            long elapsedMillis =
144 +                (System.nanoTime() - t0) / (1000L * 1000L);
145 +            if (elapsedMillis >= profileThreshold)
146 +                System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
147 +        }
148 +    }
149 +
150      /**
151 <     * Runs all JSR166 unit tests using junit.textui.TestRunner
151 >     * Runs all JSR166 unit tests using junit.textui.TestRunner.
152 >     * Optional command line arg provides the number of iterations to
153 >     * repeat running the tests.
154       */
155      public static void main(String[] args) {
156          if (useSecurityManager) {
# Line 116 | Line 169 | public class JSR166TestCase extends Test
169          System.exit(0);
170      }
171  
172 +    public static TestSuite newTestSuite(Object... suiteOrClasses) {
173 +        TestSuite suite = new TestSuite();
174 +        for (Object suiteOrClass : suiteOrClasses) {
175 +            if (suiteOrClass instanceof TestSuite)
176 +                suite.addTest((TestSuite) suiteOrClass);
177 +            else if (suiteOrClass instanceof Class)
178 +                suite.addTest(new TestSuite((Class<?>) suiteOrClass));
179 +            else
180 +                throw new ClassCastException("not a test suite or class");
181 +        }
182 +        return suite;
183 +    }
184 +
185 +    public static void addNamedTestClasses(TestSuite suite,
186 +                                           String... testClassNames) {
187 +        for (String testClassName : testClassNames) {
188 +            try {
189 +                Class<?> testClass = Class.forName(testClassName);
190 +                Method m = testClass.getDeclaredMethod("suite",
191 +                                                       new Class<?>[0]);
192 +                suite.addTest(newTestSuite((Test)m.invoke(null)));
193 +            } catch (Exception e) {
194 +                throw new Error("Missing test class", e);
195 +            }
196 +        }
197 +    }
198 +
199 +    public static final double JAVA_CLASS_VERSION;
200 +    static {
201 +        try {
202 +            JAVA_CLASS_VERSION = java.security.AccessController.doPrivileged(
203 +                new java.security.PrivilegedAction<Double>() {
204 +                public Double run() {
205 +                    return Double.valueOf(System.getProperty("java.class.version"));}});
206 +        } catch (Throwable t) {
207 +            throw new Error(t);
208 +        }
209 +    }
210 +
211 +    public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
212 +    public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
213 +    public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
214 +
215      /**
216 <     * Collects all JSR166 unit tests as one suite
216 >     * Collects all JSR166 unit tests as one suite.
217       */
218      public static Test suite() {
219 <        TestSuite suite = new TestSuite("JSR166 Unit Tests");
220 <
221 <        suite.addTest(ForkJoinPoolTest.suite());
222 <        suite.addTest(ForkJoinTaskTest.suite());
223 <        suite.addTest(RecursiveActionTest.suite());
224 <        suite.addTest(RecursiveTaskTest.suite());
225 <        suite.addTest(LinkedTransferQueueTest.suite());
226 <        suite.addTest(PhaserTest.suite());
227 <        suite.addTest(ThreadLocalRandomTest.suite());
228 <        suite.addTest(AbstractExecutorServiceTest.suite());
229 <        suite.addTest(AbstractQueueTest.suite());
230 <        suite.addTest(AbstractQueuedSynchronizerTest.suite());
231 <        suite.addTest(AbstractQueuedLongSynchronizerTest.suite());
232 <        suite.addTest(ArrayBlockingQueueTest.suite());
233 <        suite.addTest(ArrayDequeTest.suite());
234 <        suite.addTest(AtomicBooleanTest.suite());
235 <        suite.addTest(AtomicIntegerArrayTest.suite());
236 <        suite.addTest(AtomicIntegerFieldUpdaterTest.suite());
237 <        suite.addTest(AtomicIntegerTest.suite());
238 <        suite.addTest(AtomicLongArrayTest.suite());
239 <        suite.addTest(AtomicLongFieldUpdaterTest.suite());
240 <        suite.addTest(AtomicLongTest.suite());
241 <        suite.addTest(AtomicMarkableReferenceTest.suite());
242 <        suite.addTest(AtomicReferenceArrayTest.suite());
243 <        suite.addTest(AtomicReferenceFieldUpdaterTest.suite());
244 <        suite.addTest(AtomicReferenceTest.suite());
245 <        suite.addTest(AtomicStampedReferenceTest.suite());
246 <        suite.addTest(ConcurrentHashMapTest.suite());
247 <        suite.addTest(ConcurrentLinkedDequeTest.suite());
248 <        suite.addTest(ConcurrentLinkedQueueTest.suite());
249 <        suite.addTest(ConcurrentSkipListMapTest.suite());
250 <        suite.addTest(ConcurrentSkipListSubMapTest.suite());
251 <        suite.addTest(ConcurrentSkipListSetTest.suite());
252 <        suite.addTest(ConcurrentSkipListSubSetTest.suite());
253 <        suite.addTest(CopyOnWriteArrayListTest.suite());
254 <        suite.addTest(CopyOnWriteArraySetTest.suite());
255 <        suite.addTest(CountDownLatchTest.suite());
256 <        suite.addTest(CyclicBarrierTest.suite());
257 <        suite.addTest(DelayQueueTest.suite());
258 <        suite.addTest(EntryTest.suite());
259 <        suite.addTest(ExchangerTest.suite());
260 <        suite.addTest(ExecutorsTest.suite());
261 <        suite.addTest(ExecutorCompletionServiceTest.suite());
262 <        suite.addTest(FutureTaskTest.suite());
263 <        suite.addTest(LinkedBlockingDequeTest.suite());
264 <        suite.addTest(LinkedBlockingQueueTest.suite());
265 <        suite.addTest(LinkedListTest.suite());
266 <        suite.addTest(LockSupportTest.suite());
267 <        suite.addTest(PriorityBlockingQueueTest.suite());
268 <        suite.addTest(PriorityQueueTest.suite());
269 <        suite.addTest(ReentrantLockTest.suite());
270 <        suite.addTest(ReentrantReadWriteLockTest.suite());
271 <        suite.addTest(ScheduledExecutorTest.suite());
272 <        suite.addTest(ScheduledExecutorSubclassTest.suite());
273 <        suite.addTest(SemaphoreTest.suite());
274 <        suite.addTest(SynchronousQueueTest.suite());
275 <        suite.addTest(SystemTest.suite());
276 <        suite.addTest(ThreadLocalTest.suite());
277 <        suite.addTest(ThreadPoolExecutorTest.suite());
278 <        suite.addTest(ThreadPoolExecutorSubclassTest.suite());
279 <        suite.addTest(ThreadTest.suite());
280 <        suite.addTest(TimeUnitTest.suite());
281 <        suite.addTest(TreeMapTest.suite());
282 <        suite.addTest(TreeSetTest.suite());
283 <        suite.addTest(TreeSubMapTest.suite());
284 <        suite.addTest(TreeSubSetTest.suite());
219 >        // Java7+ test classes
220 >        TestSuite suite = newTestSuite(
221 >            ForkJoinPoolTest.suite(),
222 >            ForkJoinTaskTest.suite(),
223 >            RecursiveActionTest.suite(),
224 >            RecursiveTaskTest.suite(),
225 >            LinkedTransferQueueTest.suite(),
226 >            PhaserTest.suite(),
227 >            ThreadLocalRandomTest.suite(),
228 >            AbstractExecutorServiceTest.suite(),
229 >            AbstractQueueTest.suite(),
230 >            AbstractQueuedSynchronizerTest.suite(),
231 >            AbstractQueuedLongSynchronizerTest.suite(),
232 >            ArrayBlockingQueueTest.suite(),
233 >            ArrayDequeTest.suite(),
234 >            AtomicBooleanTest.suite(),
235 >            AtomicIntegerArrayTest.suite(),
236 >            AtomicIntegerFieldUpdaterTest.suite(),
237 >            AtomicIntegerTest.suite(),
238 >            AtomicLongArrayTest.suite(),
239 >            AtomicLongFieldUpdaterTest.suite(),
240 >            AtomicLongTest.suite(),
241 >            AtomicMarkableReferenceTest.suite(),
242 >            AtomicReferenceArrayTest.suite(),
243 >            AtomicReferenceFieldUpdaterTest.suite(),
244 >            AtomicReferenceTest.suite(),
245 >            AtomicStampedReferenceTest.suite(),
246 >            ConcurrentHashMapTest.suite(),
247 >            ConcurrentLinkedDequeTest.suite(),
248 >            ConcurrentLinkedQueueTest.suite(),
249 >            ConcurrentSkipListMapTest.suite(),
250 >            ConcurrentSkipListSubMapTest.suite(),
251 >            ConcurrentSkipListSetTest.suite(),
252 >            ConcurrentSkipListSubSetTest.suite(),
253 >            CopyOnWriteArrayListTest.suite(),
254 >            CopyOnWriteArraySetTest.suite(),
255 >            CountDownLatchTest.suite(),
256 >            CyclicBarrierTest.suite(),
257 >            DelayQueueTest.suite(),
258 >            EntryTest.suite(),
259 >            ExchangerTest.suite(),
260 >            ExecutorsTest.suite(),
261 >            ExecutorCompletionServiceTest.suite(),
262 >            FutureTaskTest.suite(),
263 >            LinkedBlockingDequeTest.suite(),
264 >            LinkedBlockingQueueTest.suite(),
265 >            LinkedListTest.suite(),
266 >            LockSupportTest.suite(),
267 >            PriorityBlockingQueueTest.suite(),
268 >            PriorityQueueTest.suite(),
269 >            ReentrantLockTest.suite(),
270 >            ReentrantReadWriteLockTest.suite(),
271 >            ScheduledExecutorTest.suite(),
272 >            ScheduledExecutorSubclassTest.suite(),
273 >            SemaphoreTest.suite(),
274 >            SynchronousQueueTest.suite(),
275 >            SystemTest.suite(),
276 >            ThreadLocalTest.suite(),
277 >            ThreadPoolExecutorTest.suite(),
278 >            ThreadPoolExecutorSubclassTest.suite(),
279 >            ThreadTest.suite(),
280 >            TimeUnitTest.suite(),
281 >            TreeMapTest.suite(),
282 >            TreeSetTest.suite(),
283 >            TreeSubMapTest.suite(),
284 >            TreeSubSetTest.suite());
285 >
286 >        // Java8+ test classes
287 >        if (atLeastJava8()) {
288 >            String[] java8TestClassNames = {
289 >                "CompletableFutureTest",
290 >                "ForkJoinPool8Test",
291 >                "StampedLockTest",
292 >            };
293 >            addNamedTestClasses(suite, java8TestClassNames);
294 >        }
295  
296          return suite;
297      }
# Line 205 | Line 311 | public class JSR166TestCase extends Test
311          return 50;
312      }
313  
208
314      /**
315       * Sets delays as multiples of SHORT_DELAY.
316       */
# Line 213 | Line 318 | public class JSR166TestCase extends Test
318          SHORT_DELAY_MS = getShortDelay();
319          SMALL_DELAY_MS  = SHORT_DELAY_MS * 5;
320          MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
321 <        LONG_DELAY_MS   = SHORT_DELAY_MS * 50;
321 >        LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
322 >    }
323 >
324 >    /**
325 >     * Returns a timeout in milliseconds to be used in tests that
326 >     * verify that operations block or time out.
327 >     */
328 >    long timeoutMillis() {
329 >        return SHORT_DELAY_MS / 4;
330 >    }
331 >
332 >    /**
333 >     * Returns a new Date instance representing a time delayMillis
334 >     * milliseconds in the future.
335 >     */
336 >    Date delayedDate(long delayMillis) {
337 >        return new Date(System.currentTimeMillis() + delayMillis);
338      }
339  
340      /**
# Line 237 | Line 358 | public class JSR166TestCase extends Test
358      }
359  
360      /**
361 +     * Extra checks that get done for all test cases.
362 +     *
363       * Triggers test case failure if any thread assertions have failed,
364       * by rethrowing, in the test harness thread, any exception recorded
365       * earlier by threadRecordFailure.
366 +     *
367 +     * Triggers test case failure if interrupt status is set in the main thread.
368       */
369      public void tearDown() throws Exception {
370 <        Throwable t = threadFailure.get();
370 >        Throwable t = threadFailure.getAndSet(null);
371          if (t != null) {
372              if (t instanceof Error)
373                  throw (Error) t;
# Line 257 | Line 382 | public class JSR166TestCase extends Test
382                  throw afe;
383              }
384          }
385 +
386 +        if (Thread.interrupted())
387 +            throw new AssertionFailedError("interrupt status set in main thread");
388 +
389 +        checkForkJoinPoolThreadLeaks();
390 +    }
391 +
392 +    /**
393 +     * Find missing try { ... } finally { joinPool(e); }
394 +     */
395 +    void checkForkJoinPoolThreadLeaks() throws InterruptedException {
396 +        Thread[] survivors = new Thread[5];
397 +        int count = Thread.enumerate(survivors);
398 +        for (int i = 0; i < count; i++) {
399 +            Thread thread = survivors[i];
400 +            String name = thread.getName();
401 +            if (name.startsWith("ForkJoinPool-")) {
402 +                // give thread some time to terminate
403 +                thread.join(LONG_DELAY_MS);
404 +                if (!thread.isAlive()) continue;
405 +                thread.stop();
406 +                throw new AssertionFailedError
407 +                    (String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n",
408 +                                   toString(), name));
409 +            }
410 +        }
411      }
412  
413      /**
# Line 388 | Line 539 | public class JSR166TestCase extends Test
539          else {
540              AssertionFailedError afe =
541                  new AssertionFailedError("unexpected exception: " + t);
542 <            t.initCause(t);
542 >            afe.initCause(t);
543              throw afe;
544          }
545      }
546  
547      /**
548 +     * Delays, via Thread.sleep, for the given millisecond delay, but
549 +     * if the sleep is shorter than specified, may re-sleep or yield
550 +     * until time elapses.
551 +     */
552 +    static void delay(long millis) throws InterruptedException {
553 +        long startTime = System.nanoTime();
554 +        long ns = millis * 1000 * 1000;
555 +        for (;;) {
556 +            if (millis > 0L)
557 +                Thread.sleep(millis);
558 +            else // too short to sleep
559 +                Thread.yield();
560 +            long d = ns - (System.nanoTime() - startTime);
561 +            if (d > 0L)
562 +                millis = d / (1000 * 1000);
563 +            else
564 +                break;
565 +        }
566 +    }
567 +
568 +    /**
569       * Waits out termination of a thread pool or fails doing so.
570       */
571 <    public void joinPool(ExecutorService exec) {
571 >    void joinPool(ExecutorService exec) {
572          try {
573              exec.shutdown();
574              assertTrue("ExecutorService did not terminate in a timely manner",
575 <                       exec.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
575 >                       exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS));
576          } catch (SecurityException ok) {
577              // Allowed in case test doesn't have privs
578          } catch (InterruptedException ie) {
# Line 408 | Line 580 | public class JSR166TestCase extends Test
580          }
581      }
582  
583 +    /**
584 +     * A debugging tool to print all stack traces, as jstack does.
585 +     */
586 +    static void printAllStackTraces() {
587 +        for (ThreadInfo info :
588 +                 ManagementFactory.getThreadMXBean()
589 +                 .dumpAllThreads(true, true))
590 +            System.err.print(info);
591 +    }
592 +
593 +    /**
594 +     * Checks that thread does not terminate within the default
595 +     * millisecond delay of {@code timeoutMillis()}.
596 +     */
597 +    void assertThreadStaysAlive(Thread thread) {
598 +        assertThreadStaysAlive(thread, timeoutMillis());
599 +    }
600 +
601 +    /**
602 +     * Checks that thread does not terminate within the given millisecond delay.
603 +     */
604 +    void assertThreadStaysAlive(Thread thread, long millis) {
605 +        try {
606 +            // No need to optimize the failing case via Thread.join.
607 +            delay(millis);
608 +            assertTrue(thread.isAlive());
609 +        } catch (InterruptedException ie) {
610 +            fail("Unexpected InterruptedException");
611 +        }
612 +    }
613 +
614 +    /**
615 +     * Checks that the threads do not terminate within the default
616 +     * millisecond delay of {@code timeoutMillis()}.
617 +     */
618 +    void assertThreadsStayAlive(Thread... threads) {
619 +        assertThreadsStayAlive(timeoutMillis(), threads);
620 +    }
621 +
622 +    /**
623 +     * Checks that the threads do not terminate within the given millisecond delay.
624 +     */
625 +    void assertThreadsStayAlive(long millis, Thread... threads) {
626 +        try {
627 +            // No need to optimize the failing case via Thread.join.
628 +            delay(millis);
629 +            for (Thread thread : threads)
630 +                assertTrue(thread.isAlive());
631 +        } catch (InterruptedException ie) {
632 +            fail("Unexpected InterruptedException");
633 +        }
634 +    }
635 +
636 +    /**
637 +     * Checks that future.get times out, with the default timeout of
638 +     * {@code timeoutMillis()}.
639 +     */
640 +    void assertFutureTimesOut(Future future) {
641 +        assertFutureTimesOut(future, timeoutMillis());
642 +    }
643 +
644 +    /**
645 +     * Checks that future.get times out, with the given millisecond timeout.
646 +     */
647 +    void assertFutureTimesOut(Future future, long timeoutMillis) {
648 +        long startTime = System.nanoTime();
649 +        try {
650 +            future.get(timeoutMillis, MILLISECONDS);
651 +            shouldThrow();
652 +        } catch (TimeoutException success) {
653 +        } catch (Exception e) {
654 +            threadUnexpectedException(e);
655 +        } finally { future.cancel(true); }
656 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
657 +    }
658  
659      /**
660       * Fails with message "should throw exception".
# Line 460 | Line 707 | public class JSR166TestCase extends Test
707          SecurityManager sm = System.getSecurityManager();
708          if (sm == null) {
709              r.run();
710 +        }
711 +        runWithSecurityManagerWithPermissions(r, permissions);
712 +    }
713 +
714 +    /**
715 +     * Runs Runnable r with a security policy that permits precisely
716 +     * the specified permissions.  If there is no current security
717 +     * manager, a temporary one is set for the duration of the
718 +     * Runnable.  We require that any security manager permit
719 +     * getPolicy/setPolicy.
720 +     */
721 +    public void runWithSecurityManagerWithPermissions(Runnable r,
722 +                                                      Permission... permissions) {
723 +        SecurityManager sm = System.getSecurityManager();
724 +        if (sm == null) {
725              Policy savedPolicy = Policy.getPolicy();
726              try {
727                  Policy.setPolicy(permissivePolicy());
728                  System.setSecurityManager(new SecurityManager());
729 <                runWithPermissions(r, permissions);
729 >                runWithSecurityManagerWithPermissions(r, permissions);
730              } finally {
731                  System.setSecurityManager(null);
732                  Policy.setPolicy(savedPolicy);
# Line 512 | Line 774 | public class JSR166TestCase extends Test
774              return perms.implies(p);
775          }
776          public void refresh() {}
777 +        public String toString() {
778 +            List<Permission> ps = new ArrayList<Permission>();
779 +            for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
780 +                ps.add(e.nextElement());
781 +            return "AdjustablePolicy with permissions " + ps;
782 +        }
783      }
784  
785      /**
# Line 534 | Line 802 | public class JSR166TestCase extends Test
802      }
803  
804      /**
805 <     * Sleep until the timeout has elapsed, or interrupted.
806 <     * Does <em>NOT</em> throw InterruptedException.
805 >     * Sleeps until the given time has elapsed.
806 >     * Throws AssertionFailedError if interrupted.
807       */
808 <    void sleepTillInterrupted(long timeoutMillis) {
808 >    void sleep(long millis) {
809          try {
810 <            Thread.sleep(timeoutMillis);
811 <        } catch (InterruptedException wakeup) {}
810 >            delay(millis);
811 >        } catch (InterruptedException ie) {
812 >            AssertionFailedError afe =
813 >                new AssertionFailedError("Unexpected InterruptedException");
814 >            afe.initCause(ie);
815 >            throw afe;
816 >        }
817 >    }
818 >
819 >    /**
820 >     * Spin-waits up to the specified number of milliseconds for the given
821 >     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
822 >     */
823 >    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
824 >        long startTime = System.nanoTime();
825 >        for (;;) {
826 >            Thread.State s = thread.getState();
827 >            if (s == Thread.State.BLOCKED ||
828 >                s == Thread.State.WAITING ||
829 >                s == Thread.State.TIMED_WAITING)
830 >                return;
831 >            else if (s == Thread.State.TERMINATED)
832 >                fail("Unexpected thread termination");
833 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
834 >                threadAssertTrue(thread.isAlive());
835 >                return;
836 >            }
837 >            Thread.yield();
838 >        }
839 >    }
840 >
841 >    /**
842 >     * Waits up to LONG_DELAY_MS for the given thread to enter a wait
843 >     * state: BLOCKED, WAITING, or TIMED_WAITING.
844 >     */
845 >    void waitForThreadToEnterWaitState(Thread thread) {
846 >        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
847 >    }
848 >
849 >    /**
850 >     * Returns the number of milliseconds since time given by
851 >     * startNanoTime, which must have been previously returned from a
852 >     * call to {@link System.nanoTime()}.
853 >     */
854 >    long millisElapsedSince(long startNanoTime) {
855 >        return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
856      }
857  
858      /**
# Line 553 | Line 865 | public class JSR166TestCase extends Test
865          return t;
866      }
867  
868 +    /**
869 +     * Waits for the specified time (in milliseconds) for the thread
870 +     * to terminate (using {@link Thread#join(long)}), else interrupts
871 +     * the thread (in the hope that it may terminate later) and fails.
872 +     */
873 +    void awaitTermination(Thread t, long timeoutMillis) {
874 +        try {
875 +            t.join(timeoutMillis);
876 +        } catch (InterruptedException ie) {
877 +            threadUnexpectedException(ie);
878 +        } finally {
879 +            if (t.getState() != Thread.State.TERMINATED) {
880 +                t.interrupt();
881 +                fail("Test timed out");
882 +            }
883 +        }
884 +    }
885 +
886 +    /**
887 +     * Waits for LONG_DELAY_MS milliseconds for the thread to
888 +     * terminate (using {@link Thread#join(long)}), else interrupts
889 +     * the thread (in the hope that it may terminate later) and fails.
890 +     */
891 +    void awaitTermination(Thread t) {
892 +        awaitTermination(t, LONG_DELAY_MS);
893 +    }
894 +
895      // Some convenient Runnable classes
896  
897      public abstract class CheckedRunnable implements Runnable {
# Line 615 | Line 954 | public class JSR166TestCase extends Test
954                  realRun();
955                  threadShouldThrow("InterruptedException");
956              } catch (InterruptedException success) {
957 +                threadAssertFalse(Thread.interrupted());
958              } catch (Throwable t) {
959                  threadUnexpectedException(t);
960              }
# Line 644 | Line 984 | public class JSR166TestCase extends Test
984                  threadShouldThrow("InterruptedException");
985                  return result;
986              } catch (InterruptedException success) {
987 +                threadAssertFalse(Thread.interrupted());
988              } catch (Throwable t) {
989                  threadUnexpectedException(t);
990              }
# Line 667 | Line 1008 | public class JSR166TestCase extends Test
1008  
1009      public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
1010          return new CheckedCallable<String>() {
1011 <            public String realCall() {
1011 >            protected String realCall() {
1012                  try {
1013                      latch.await();
1014                  } catch (InterruptedException quittingTime) {}
# Line 675 | Line 1016 | public class JSR166TestCase extends Test
1016              }};
1017      }
1018  
1019 +    public Runnable awaiter(final CountDownLatch latch) {
1020 +        return new CheckedRunnable() {
1021 +            public void realRun() throws InterruptedException {
1022 +                await(latch);
1023 +            }};
1024 +    }
1025 +
1026 +    public void await(CountDownLatch latch) {
1027 +        try {
1028 +            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1029 +        } catch (Throwable t) {
1030 +            threadUnexpectedException(t);
1031 +        }
1032 +    }
1033 +
1034 +    public void await(Semaphore semaphore) {
1035 +        try {
1036 +            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1037 +        } catch (Throwable t) {
1038 +            threadUnexpectedException(t);
1039 +        }
1040 +    }
1041 +
1042 + //     /**
1043 + //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1044 + //      */
1045 + //     public void await(AtomicBoolean flag) {
1046 + //         await(flag, LONG_DELAY_MS);
1047 + //     }
1048 +
1049 + //     /**
1050 + //      * Spin-waits up to the specified timeout until flag becomes true.
1051 + //      */
1052 + //     public void await(AtomicBoolean flag, long timeoutMillis) {
1053 + //         long startTime = System.nanoTime();
1054 + //         while (!flag.get()) {
1055 + //             if (millisElapsedSince(startTime) > timeoutMillis)
1056 + //                 throw new AssertionFailedError("timed out");
1057 + //             Thread.yield();
1058 + //         }
1059 + //     }
1060 +
1061      public static class NPETask implements Callable<String> {
1062          public String call() { throw new NullPointerException(); }
1063      }
# Line 685 | Line 1068 | public class JSR166TestCase extends Test
1068  
1069      public class ShortRunnable extends CheckedRunnable {
1070          protected void realRun() throws Throwable {
1071 <            Thread.sleep(SHORT_DELAY_MS);
1071 >            delay(SHORT_DELAY_MS);
1072          }
1073      }
1074  
1075      public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1076          protected void realRun() throws InterruptedException {
1077 <            Thread.sleep(SHORT_DELAY_MS);
1077 >            delay(SHORT_DELAY_MS);
1078          }
1079      }
1080  
1081      public class SmallRunnable extends CheckedRunnable {
1082          protected void realRun() throws Throwable {
1083 <            Thread.sleep(SMALL_DELAY_MS);
1083 >            delay(SMALL_DELAY_MS);
1084          }
1085      }
1086  
1087      public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1088          protected void realRun() {
1089              try {
1090 <                Thread.sleep(SMALL_DELAY_MS);
1090 >                delay(SMALL_DELAY_MS);
1091              } catch (InterruptedException ok) {}
1092          }
1093      }
1094  
1095      public class SmallCallable extends CheckedCallable {
1096          protected Object realCall() throws InterruptedException {
1097 <            Thread.sleep(SMALL_DELAY_MS);
1097 >            delay(SMALL_DELAY_MS);
1098              return Boolean.TRUE;
1099          }
1100      }
1101  
1102      public class MediumRunnable extends CheckedRunnable {
1103          protected void realRun() throws Throwable {
1104 <            Thread.sleep(MEDIUM_DELAY_MS);
1104 >            delay(MEDIUM_DELAY_MS);
1105          }
1106      }
1107  
1108      public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1109          protected void realRun() throws InterruptedException {
1110 <            Thread.sleep(MEDIUM_DELAY_MS);
1110 >            delay(MEDIUM_DELAY_MS);
1111          }
1112      }
1113  
1114 +    public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1115 +        return new CheckedRunnable() {
1116 +            protected void realRun() {
1117 +                try {
1118 +                    delay(timeoutMillis);
1119 +                } catch (InterruptedException ok) {}
1120 +            }};
1121 +    }
1122 +
1123      public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1124          protected void realRun() {
1125              try {
1126 <                Thread.sleep(MEDIUM_DELAY_MS);
1126 >                delay(MEDIUM_DELAY_MS);
1127              } catch (InterruptedException ok) {}
1128          }
1129      }
# Line 739 | Line 1131 | public class JSR166TestCase extends Test
1131      public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1132          protected void realRun() {
1133              try {
1134 <                Thread.sleep(LONG_DELAY_MS);
1134 >                delay(LONG_DELAY_MS);
1135              } catch (InterruptedException ok) {}
1136          }
1137      }
# Line 753 | Line 1145 | public class JSR166TestCase extends Test
1145          }
1146      }
1147  
1148 +    public interface TrackedRunnable extends Runnable {
1149 +        boolean isDone();
1150 +    }
1151 +
1152 +    public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
1153 +        return new TrackedRunnable() {
1154 +                private volatile boolean done = false;
1155 +                public boolean isDone() { return done; }
1156 +                public void run() {
1157 +                    try {
1158 +                        delay(timeoutMillis);
1159 +                        done = true;
1160 +                    } catch (InterruptedException ok) {}
1161 +                }
1162 +            };
1163 +    }
1164 +
1165      public static class TrackedShortRunnable implements Runnable {
1166          public volatile boolean done = false;
1167          public void run() {
1168              try {
1169 <                Thread.sleep(SMALL_DELAY_MS);
1169 >                delay(SHORT_DELAY_MS);
1170 >                done = true;
1171 >            } catch (InterruptedException ok) {}
1172 >        }
1173 >    }
1174 >
1175 >    public static class TrackedSmallRunnable implements Runnable {
1176 >        public volatile boolean done = false;
1177 >        public void run() {
1178 >            try {
1179 >                delay(SMALL_DELAY_MS);
1180                  done = true;
1181              } catch (InterruptedException ok) {}
1182          }
# Line 767 | Line 1186 | public class JSR166TestCase extends Test
1186          public volatile boolean done = false;
1187          public void run() {
1188              try {
1189 <                Thread.sleep(MEDIUM_DELAY_MS);
1189 >                delay(MEDIUM_DELAY_MS);
1190                  done = true;
1191              } catch (InterruptedException ok) {}
1192          }
# Line 777 | Line 1196 | public class JSR166TestCase extends Test
1196          public volatile boolean done = false;
1197          public void run() {
1198              try {
1199 <                Thread.sleep(LONG_DELAY_MS);
1199 >                delay(LONG_DELAY_MS);
1200                  done = true;
1201              } catch (InterruptedException ok) {}
1202          }
# Line 794 | Line 1213 | public class JSR166TestCase extends Test
1213          public volatile boolean done = false;
1214          public Object call() {
1215              try {
1216 <                Thread.sleep(SMALL_DELAY_MS);
1216 >                delay(SMALL_DELAY_MS);
1217                  done = true;
1218              } catch (InterruptedException ok) {}
1219              return Boolean.TRUE;
# Line 840 | Line 1259 | public class JSR166TestCase extends Test
1259                                        ThreadPoolExecutor executor) {}
1260      }
1261  
1262 +    /**
1263 +     * A CyclicBarrier that uses timed await and fails with
1264 +     * AssertionFailedErrors instead of throwing checked exceptions.
1265 +     */
1266 +    public class CheckedBarrier extends CyclicBarrier {
1267 +        public CheckedBarrier(int parties) { super(parties); }
1268 +
1269 +        public int await() {
1270 +            try {
1271 +                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1272 +            } catch (TimeoutException e) {
1273 +                throw new AssertionFailedError("timed out");
1274 +            } catch (Exception e) {
1275 +                AssertionFailedError afe =
1276 +                    new AssertionFailedError("Unexpected exception: " + e);
1277 +                afe.initCause(e);
1278 +                throw afe;
1279 +            }
1280 +        }
1281 +    }
1282 +
1283 +    void checkEmpty(BlockingQueue q) {
1284 +        try {
1285 +            assertTrue(q.isEmpty());
1286 +            assertEquals(0, q.size());
1287 +            assertNull(q.peek());
1288 +            assertNull(q.poll());
1289 +            assertNull(q.poll(0, MILLISECONDS));
1290 +            assertEquals(q.toString(), "[]");
1291 +            assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1292 +            assertFalse(q.iterator().hasNext());
1293 +            try {
1294 +                q.element();
1295 +                shouldThrow();
1296 +            } catch (NoSuchElementException success) {}
1297 +            try {
1298 +                q.iterator().next();
1299 +                shouldThrow();
1300 +            } catch (NoSuchElementException success) {}
1301 +            try {
1302 +                q.remove();
1303 +                shouldThrow();
1304 +            } catch (NoSuchElementException success) {}
1305 +        } catch (InterruptedException ie) {
1306 +            threadUnexpectedException(ie);
1307 +        }
1308 +    }
1309 +
1310 +    void assertSerialEquals(Object x, Object y) {
1311 +        assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1312 +    }
1313 +
1314 +    void assertNotSerialEquals(Object x, Object y) {
1315 +        assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1316 +    }
1317 +
1318 +    byte[] serialBytes(Object o) {
1319 +        try {
1320 +            ByteArrayOutputStream bos = new ByteArrayOutputStream();
1321 +            ObjectOutputStream oos = new ObjectOutputStream(bos);
1322 +            oos.writeObject(o);
1323 +            oos.flush();
1324 +            oos.close();
1325 +            return bos.toByteArray();
1326 +        } catch (Throwable t) {
1327 +            threadUnexpectedException(t);
1328 +            return new byte[0];
1329 +        }
1330 +    }
1331 +
1332 +    @SuppressWarnings("unchecked")
1333 +    <T> T serialClone(T o) {
1334 +        try {
1335 +            ObjectInputStream ois = new ObjectInputStream
1336 +                (new ByteArrayInputStream(serialBytes(o)));
1337 +            T clone = (T) ois.readObject();
1338 +            assertSame(o.getClass(), clone.getClass());
1339 +            return clone;
1340 +        } catch (Throwable t) {
1341 +            threadUnexpectedException(t);
1342 +            return null;
1343 +        }
1344 +    }
1345   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines