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.98 by jsr166, Sun Feb 3 06:20:32 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 >                "StampedLockTest",
290 >            };
291 >            addNamedTestClasses(suite, java8TestClassNames);
292 >        }
293  
294          return suite;
295      }
# Line 205 | Line 309 | public class JSR166TestCase extends Test
309          return 50;
310      }
311  
208
312      /**
313       * Sets delays as multiples of SHORT_DELAY.
314       */
# Line 213 | Line 316 | public class JSR166TestCase extends Test
316          SHORT_DELAY_MS = getShortDelay();
317          SMALL_DELAY_MS  = SHORT_DELAY_MS * 5;
318          MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
319 <        LONG_DELAY_MS   = SHORT_DELAY_MS * 50;
319 >        LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
320 >    }
321 >
322 >    /**
323 >     * Returns a timeout in milliseconds to be used in tests that
324 >     * verify that operations block or time out.
325 >     */
326 >    long timeoutMillis() {
327 >        return SHORT_DELAY_MS / 4;
328 >    }
329 >
330 >    /**
331 >     * Returns a new Date instance representing a time delayMillis
332 >     * milliseconds in the future.
333 >     */
334 >    Date delayedDate(long delayMillis) {
335 >        return new Date(System.currentTimeMillis() + delayMillis);
336      }
337  
338      /**
# Line 237 | Line 356 | public class JSR166TestCase extends Test
356      }
357  
358      /**
359 +     * Extra checks that get done for all test cases.
360 +     *
361       * Triggers test case failure if any thread assertions have failed,
362       * by rethrowing, in the test harness thread, any exception recorded
363       * earlier by threadRecordFailure.
364 +     *
365 +     * Triggers test case failure if interrupt status is set in the main thread.
366       */
367      public void tearDown() throws Exception {
368 <        Throwable t = threadFailure.get();
368 >        Throwable t = threadFailure.getAndSet(null);
369          if (t != null) {
370              if (t instanceof Error)
371                  throw (Error) t;
# Line 257 | Line 380 | public class JSR166TestCase extends Test
380                  throw afe;
381              }
382          }
383 +
384 +        if (Thread.interrupted())
385 +            throw new AssertionFailedError("interrupt status set in main thread");
386      }
387  
388      /**
# Line 388 | Line 514 | public class JSR166TestCase extends Test
514          else {
515              AssertionFailedError afe =
516                  new AssertionFailedError("unexpected exception: " + t);
517 <            t.initCause(t);
517 >            afe.initCause(t);
518              throw afe;
519          }
520      }
521  
522      /**
523 +     * Delays, via Thread.sleep, for the given millisecond delay, but
524 +     * if the sleep is shorter than specified, may re-sleep or yield
525 +     * until time elapses.
526 +     */
527 +    static void delay(long millis) throws InterruptedException {
528 +        long startTime = System.nanoTime();
529 +        long ns = millis * 1000 * 1000;
530 +        for (;;) {
531 +            if (millis > 0L)
532 +                Thread.sleep(millis);
533 +            else // too short to sleep
534 +                Thread.yield();
535 +            long d = ns - (System.nanoTime() - startTime);
536 +            if (d > 0L)
537 +                millis = d / (1000 * 1000);
538 +            else
539 +                break;
540 +        }
541 +    }
542 +
543 +    /**
544       * Waits out termination of a thread pool or fails doing so.
545       */
546 <    public void joinPool(ExecutorService exec) {
546 >    void joinPool(ExecutorService exec) {
547          try {
548              exec.shutdown();
549              assertTrue("ExecutorService did not terminate in a timely manner",
550 <                       exec.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
550 >                       exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS));
551          } catch (SecurityException ok) {
552              // Allowed in case test doesn't have privs
553          } catch (InterruptedException ie) {
# Line 408 | Line 555 | public class JSR166TestCase extends Test
555          }
556      }
557  
558 +    /**
559 +     * A debugging tool to print all stack traces, as jstack does.
560 +     */
561 +    static void printAllStackTraces() {
562 +        for (ThreadInfo info :
563 +                 ManagementFactory.getThreadMXBean()
564 +                 .dumpAllThreads(true, true))
565 +            System.err.print(info);
566 +    }
567 +
568 +    /**
569 +     * Checks that thread does not terminate within the default
570 +     * millisecond delay of {@code timeoutMillis()}.
571 +     */
572 +    void assertThreadStaysAlive(Thread thread) {
573 +        assertThreadStaysAlive(thread, timeoutMillis());
574 +    }
575 +
576 +    /**
577 +     * Checks that thread does not terminate within the given millisecond delay.
578 +     */
579 +    void assertThreadStaysAlive(Thread thread, long millis) {
580 +        try {
581 +            // No need to optimize the failing case via Thread.join.
582 +            delay(millis);
583 +            assertTrue(thread.isAlive());
584 +        } catch (InterruptedException ie) {
585 +            fail("Unexpected InterruptedException");
586 +        }
587 +    }
588 +
589 +    /**
590 +     * Checks that the threads do not terminate within the default
591 +     * millisecond delay of {@code timeoutMillis()}.
592 +     */
593 +    void assertThreadsStayAlive(Thread... threads) {
594 +        assertThreadsStayAlive(timeoutMillis(), threads);
595 +    }
596 +
597 +    /**
598 +     * Checks that the threads do not terminate within the given millisecond delay.
599 +     */
600 +    void assertThreadsStayAlive(long millis, Thread... threads) {
601 +        try {
602 +            // No need to optimize the failing case via Thread.join.
603 +            delay(millis);
604 +            for (Thread thread : threads)
605 +                assertTrue(thread.isAlive());
606 +        } catch (InterruptedException ie) {
607 +            fail("Unexpected InterruptedException");
608 +        }
609 +    }
610 +
611 +    /**
612 +     * Checks that future.get times out, with the default timeout of
613 +     * {@code timeoutMillis()}.
614 +     */
615 +    void assertFutureTimesOut(Future future) {
616 +        assertFutureTimesOut(future, timeoutMillis());
617 +    }
618 +
619 +    /**
620 +     * Checks that future.get times out, with the given millisecond timeout.
621 +     */
622 +    void assertFutureTimesOut(Future future, long timeoutMillis) {
623 +        long startTime = System.nanoTime();
624 +        try {
625 +            future.get(timeoutMillis, MILLISECONDS);
626 +            shouldThrow();
627 +        } catch (TimeoutException success) {
628 +        } catch (Exception e) {
629 +            threadUnexpectedException(e);
630 +        } finally { future.cancel(true); }
631 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
632 +    }
633  
634      /**
635       * Fails with message "should throw exception".
# Line 460 | Line 682 | public class JSR166TestCase extends Test
682          SecurityManager sm = System.getSecurityManager();
683          if (sm == null) {
684              r.run();
685 +        }
686 +        runWithSecurityManagerWithPermissions(r, permissions);
687 +    }
688 +
689 +    /**
690 +     * Runs Runnable r with a security policy that permits precisely
691 +     * the specified permissions.  If there is no current security
692 +     * manager, a temporary one is set for the duration of the
693 +     * Runnable.  We require that any security manager permit
694 +     * getPolicy/setPolicy.
695 +     */
696 +    public void runWithSecurityManagerWithPermissions(Runnable r,
697 +                                                      Permission... permissions) {
698 +        SecurityManager sm = System.getSecurityManager();
699 +        if (sm == null) {
700              Policy savedPolicy = Policy.getPolicy();
701              try {
702                  Policy.setPolicy(permissivePolicy());
703                  System.setSecurityManager(new SecurityManager());
704 <                runWithPermissions(r, permissions);
704 >                runWithSecurityManagerWithPermissions(r, permissions);
705              } finally {
706                  System.setSecurityManager(null);
707                  Policy.setPolicy(savedPolicy);
# Line 512 | Line 749 | public class JSR166TestCase extends Test
749              return perms.implies(p);
750          }
751          public void refresh() {}
752 +        public String toString() {
753 +            List<Permission> ps = new ArrayList<Permission>();
754 +            for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
755 +                ps.add(e.nextElement());
756 +            return "AdjustablePolicy with permissions " + ps;
757 +        }
758      }
759  
760      /**
# Line 534 | Line 777 | public class JSR166TestCase extends Test
777      }
778  
779      /**
780 <     * Sleep until the timeout has elapsed, or interrupted.
781 <     * Does <em>NOT</em> throw InterruptedException.
780 >     * Sleeps until the given time has elapsed.
781 >     * Throws AssertionFailedError if interrupted.
782       */
783 <    void sleepTillInterrupted(long timeoutMillis) {
783 >    void sleep(long millis) {
784          try {
785 <            Thread.sleep(timeoutMillis);
786 <        } catch (InterruptedException wakeup) {}
785 >            delay(millis);
786 >        } catch (InterruptedException ie) {
787 >            AssertionFailedError afe =
788 >                new AssertionFailedError("Unexpected InterruptedException");
789 >            afe.initCause(ie);
790 >            throw afe;
791 >        }
792 >    }
793 >
794 >    /**
795 >     * Spin-waits up to the specified number of milliseconds for the given
796 >     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
797 >     */
798 >    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
799 >        long startTime = System.nanoTime();
800 >        for (;;) {
801 >            Thread.State s = thread.getState();
802 >            if (s == Thread.State.BLOCKED ||
803 >                s == Thread.State.WAITING ||
804 >                s == Thread.State.TIMED_WAITING)
805 >                return;
806 >            else if (s == Thread.State.TERMINATED)
807 >                fail("Unexpected thread termination");
808 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
809 >                threadAssertTrue(thread.isAlive());
810 >                return;
811 >            }
812 >            Thread.yield();
813 >        }
814 >    }
815 >
816 >    /**
817 >     * Waits up to LONG_DELAY_MS for the given thread to enter a wait
818 >     * state: BLOCKED, WAITING, or TIMED_WAITING.
819 >     */
820 >    void waitForThreadToEnterWaitState(Thread thread) {
821 >        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
822 >    }
823 >
824 >    /**
825 >     * Returns the number of milliseconds since time given by
826 >     * startNanoTime, which must have been previously returned from a
827 >     * call to {@link System.nanoTime()}.
828 >     */
829 >    long millisElapsedSince(long startNanoTime) {
830 >        return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
831      }
832  
833      /**
834 <     * Returns a new started Thread running the given runnable.
834 >     * Returns a new started daemon Thread running the given runnable.
835       */
836      Thread newStartedThread(Runnable runnable) {
837          Thread t = new Thread(runnable);
838 +        t.setDaemon(true);
839          t.start();
840          return t;
841      }
842  
843 +    /**
844 +     * Waits for the specified time (in milliseconds) for the thread
845 +     * to terminate (using {@link Thread#join(long)}), else interrupts
846 +     * the thread (in the hope that it may terminate later) and fails.
847 +     */
848 +    void awaitTermination(Thread t, long timeoutMillis) {
849 +        try {
850 +            t.join(timeoutMillis);
851 +        } catch (InterruptedException ie) {
852 +            threadUnexpectedException(ie);
853 +        } finally {
854 +            if (t.getState() != Thread.State.TERMINATED) {
855 +                t.interrupt();
856 +                fail("Test timed out");
857 +            }
858 +        }
859 +    }
860 +
861 +    /**
862 +     * Waits for LONG_DELAY_MS milliseconds for the thread to
863 +     * terminate (using {@link Thread#join(long)}), else interrupts
864 +     * the thread (in the hope that it may terminate later) and fails.
865 +     */
866 +    void awaitTermination(Thread t) {
867 +        awaitTermination(t, LONG_DELAY_MS);
868 +    }
869 +
870      // Some convenient Runnable classes
871  
872      public abstract class CheckedRunnable implements Runnable {
# Line 614 | Line 929 | public class JSR166TestCase extends Test
929                  realRun();
930                  threadShouldThrow("InterruptedException");
931              } catch (InterruptedException success) {
932 +                threadAssertFalse(Thread.interrupted());
933              } catch (Throwable t) {
934                  threadUnexpectedException(t);
935              }
# Line 643 | Line 959 | public class JSR166TestCase extends Test
959                  threadShouldThrow("InterruptedException");
960                  return result;
961              } catch (InterruptedException success) {
962 +                threadAssertFalse(Thread.interrupted());
963              } catch (Throwable t) {
964                  threadUnexpectedException(t);
965              }
# Line 666 | Line 983 | public class JSR166TestCase extends Test
983  
984      public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
985          return new CheckedCallable<String>() {
986 <            public String realCall() {
986 >            protected String realCall() {
987                  try {
988                      latch.await();
989                  } catch (InterruptedException quittingTime) {}
# Line 674 | Line 991 | public class JSR166TestCase extends Test
991              }};
992      }
993  
994 +    public Runnable awaiter(final CountDownLatch latch) {
995 +        return new CheckedRunnable() {
996 +            public void realRun() throws InterruptedException {
997 +                await(latch);
998 +            }};
999 +    }
1000 +
1001 +    public void await(CountDownLatch latch) {
1002 +        try {
1003 +            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1004 +        } catch (Throwable t) {
1005 +            threadUnexpectedException(t);
1006 +        }
1007 +    }
1008 +
1009 +    public void await(Semaphore semaphore) {
1010 +        try {
1011 +            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1012 +        } catch (Throwable t) {
1013 +            threadUnexpectedException(t);
1014 +        }
1015 +    }
1016 +
1017 + //     /**
1018 + //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1019 + //      */
1020 + //     public void await(AtomicBoolean flag) {
1021 + //         await(flag, LONG_DELAY_MS);
1022 + //     }
1023 +
1024 + //     /**
1025 + //      * Spin-waits up to the specified timeout until flag becomes true.
1026 + //      */
1027 + //     public void await(AtomicBoolean flag, long timeoutMillis) {
1028 + //         long startTime = System.nanoTime();
1029 + //         while (!flag.get()) {
1030 + //             if (millisElapsedSince(startTime) > timeoutMillis)
1031 + //                 throw new AssertionFailedError("timed out");
1032 + //             Thread.yield();
1033 + //         }
1034 + //     }
1035 +
1036      public static class NPETask implements Callable<String> {
1037          public String call() { throw new NullPointerException(); }
1038      }
# Line 684 | Line 1043 | public class JSR166TestCase extends Test
1043  
1044      public class ShortRunnable extends CheckedRunnable {
1045          protected void realRun() throws Throwable {
1046 <            Thread.sleep(SHORT_DELAY_MS);
1046 >            delay(SHORT_DELAY_MS);
1047          }
1048      }
1049  
1050      public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1051          protected void realRun() throws InterruptedException {
1052 <            Thread.sleep(SHORT_DELAY_MS);
1052 >            delay(SHORT_DELAY_MS);
1053          }
1054      }
1055  
1056      public class SmallRunnable extends CheckedRunnable {
1057          protected void realRun() throws Throwable {
1058 <            Thread.sleep(SMALL_DELAY_MS);
1058 >            delay(SMALL_DELAY_MS);
1059          }
1060      }
1061  
1062      public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1063          protected void realRun() {
1064              try {
1065 <                Thread.sleep(SMALL_DELAY_MS);
1065 >                delay(SMALL_DELAY_MS);
1066              } catch (InterruptedException ok) {}
1067          }
1068      }
1069  
1070      public class SmallCallable extends CheckedCallable {
1071          protected Object realCall() throws InterruptedException {
1072 <            Thread.sleep(SMALL_DELAY_MS);
1072 >            delay(SMALL_DELAY_MS);
1073              return Boolean.TRUE;
1074          }
1075      }
1076  
1077      public class MediumRunnable extends CheckedRunnable {
1078          protected void realRun() throws Throwable {
1079 <            Thread.sleep(MEDIUM_DELAY_MS);
1079 >            delay(MEDIUM_DELAY_MS);
1080          }
1081      }
1082  
1083      public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1084          protected void realRun() throws InterruptedException {
1085 <            Thread.sleep(MEDIUM_DELAY_MS);
1085 >            delay(MEDIUM_DELAY_MS);
1086          }
1087      }
1088  
1089 +    public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1090 +        return new CheckedRunnable() {
1091 +            protected void realRun() {
1092 +                try {
1093 +                    delay(timeoutMillis);
1094 +                } catch (InterruptedException ok) {}
1095 +            }};
1096 +    }
1097 +
1098      public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1099          protected void realRun() {
1100              try {
1101 <                Thread.sleep(MEDIUM_DELAY_MS);
1101 >                delay(MEDIUM_DELAY_MS);
1102              } catch (InterruptedException ok) {}
1103          }
1104      }
# Line 738 | Line 1106 | public class JSR166TestCase extends Test
1106      public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1107          protected void realRun() {
1108              try {
1109 <                Thread.sleep(LONG_DELAY_MS);
1109 >                delay(LONG_DELAY_MS);
1110              } catch (InterruptedException ok) {}
1111          }
1112      }
# Line 752 | Line 1120 | public class JSR166TestCase extends Test
1120          }
1121      }
1122  
1123 +    public interface TrackedRunnable extends Runnable {
1124 +        boolean isDone();
1125 +    }
1126 +
1127 +    public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
1128 +        return new TrackedRunnable() {
1129 +                private volatile boolean done = false;
1130 +                public boolean isDone() { return done; }
1131 +                public void run() {
1132 +                    try {
1133 +                        delay(timeoutMillis);
1134 +                        done = true;
1135 +                    } catch (InterruptedException ok) {}
1136 +                }
1137 +            };
1138 +    }
1139 +
1140      public static class TrackedShortRunnable implements Runnable {
1141          public volatile boolean done = false;
1142          public void run() {
1143              try {
1144 <                Thread.sleep(SMALL_DELAY_MS);
1144 >                delay(SHORT_DELAY_MS);
1145 >                done = true;
1146 >            } catch (InterruptedException ok) {}
1147 >        }
1148 >    }
1149 >
1150 >    public static class TrackedSmallRunnable implements Runnable {
1151 >        public volatile boolean done = false;
1152 >        public void run() {
1153 >            try {
1154 >                delay(SMALL_DELAY_MS);
1155                  done = true;
1156              } catch (InterruptedException ok) {}
1157          }
# Line 766 | Line 1161 | public class JSR166TestCase extends Test
1161          public volatile boolean done = false;
1162          public void run() {
1163              try {
1164 <                Thread.sleep(MEDIUM_DELAY_MS);
1164 >                delay(MEDIUM_DELAY_MS);
1165                  done = true;
1166              } catch (InterruptedException ok) {}
1167          }
# Line 776 | Line 1171 | public class JSR166TestCase extends Test
1171          public volatile boolean done = false;
1172          public void run() {
1173              try {
1174 <                Thread.sleep(LONG_DELAY_MS);
1174 >                delay(LONG_DELAY_MS);
1175                  done = true;
1176              } catch (InterruptedException ok) {}
1177          }
# Line 793 | Line 1188 | public class JSR166TestCase extends Test
1188          public volatile boolean done = false;
1189          public Object call() {
1190              try {
1191 <                Thread.sleep(SMALL_DELAY_MS);
1191 >                delay(SMALL_DELAY_MS);
1192                  done = true;
1193              } catch (InterruptedException ok) {}
1194              return Boolean.TRUE;
# Line 839 | Line 1234 | public class JSR166TestCase extends Test
1234                                        ThreadPoolExecutor executor) {}
1235      }
1236  
1237 +    /**
1238 +     * A CyclicBarrier that uses timed await and fails with
1239 +     * AssertionFailedErrors instead of throwing checked exceptions.
1240 +     */
1241 +    public class CheckedBarrier extends CyclicBarrier {
1242 +        public CheckedBarrier(int parties) { super(parties); }
1243 +
1244 +        public int await() {
1245 +            try {
1246 +                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1247 +            } catch (TimeoutException e) {
1248 +                throw new AssertionFailedError("timed out");
1249 +            } catch (Exception e) {
1250 +                AssertionFailedError afe =
1251 +                    new AssertionFailedError("Unexpected exception: " + e);
1252 +                afe.initCause(e);
1253 +                throw afe;
1254 +            }
1255 +        }
1256 +    }
1257 +
1258 +    void checkEmpty(BlockingQueue q) {
1259 +        try {
1260 +            assertTrue(q.isEmpty());
1261 +            assertEquals(0, q.size());
1262 +            assertNull(q.peek());
1263 +            assertNull(q.poll());
1264 +            assertNull(q.poll(0, MILLISECONDS));
1265 +            assertEquals(q.toString(), "[]");
1266 +            assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1267 +            assertFalse(q.iterator().hasNext());
1268 +            try {
1269 +                q.element();
1270 +                shouldThrow();
1271 +            } catch (NoSuchElementException success) {}
1272 +            try {
1273 +                q.iterator().next();
1274 +                shouldThrow();
1275 +            } catch (NoSuchElementException success) {}
1276 +            try {
1277 +                q.remove();
1278 +                shouldThrow();
1279 +            } catch (NoSuchElementException success) {}
1280 +        } catch (InterruptedException ie) {
1281 +            threadUnexpectedException(ie);
1282 +        }
1283 +    }
1284 +
1285 +    void assertSerialEquals(Object x, Object y) {
1286 +        assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1287 +    }
1288 +
1289 +    void assertNotSerialEquals(Object x, Object y) {
1290 +        assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1291 +    }
1292 +
1293 +    byte[] serialBytes(Object o) {
1294 +        try {
1295 +            ByteArrayOutputStream bos = new ByteArrayOutputStream();
1296 +            ObjectOutputStream oos = new ObjectOutputStream(bos);
1297 +            oos.writeObject(o);
1298 +            oos.flush();
1299 +            oos.close();
1300 +            return bos.toByteArray();
1301 +        } catch (Throwable t) {
1302 +            threadUnexpectedException(t);
1303 +            return new byte[0];
1304 +        }
1305 +    }
1306 +
1307 +    @SuppressWarnings("unchecked")
1308 +    <T> T serialClone(T o) {
1309 +        try {
1310 +            ObjectInputStream ois = new ObjectInputStream
1311 +                (new ByteArrayInputStream(serialBytes(o)));
1312 +            T clone = (T) ois.readObject();
1313 +            assertSame(o.getClass(), clone.getClass());
1314 +            return clone;
1315 +        } catch (Throwable t) {
1316 +            threadUnexpectedException(t);
1317 +            return null;
1318 +        }
1319 +    }
1320   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines