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.54 by jsr166, Fri Sep 17 00:52:36 2010 UTC vs.
Revision 1.99 by jsr166, Tue Feb 5 03:39:34 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 105 | Line 158 | public class JSR166TestCase extends Test
158              Policy.setPolicy(permissivePolicy());
159              System.setSecurityManager(new SecurityManager());
160          }
161 <        int iters = 1;
162 <        if (args.length > 0)
110 <            iters = Integer.parseInt(args[0]);
161 >        int iters = (args.length == 0) ? 1 : Integer.parseInt(args[0]);
162 >
163          Test s = suite();
164          for (int i = 0; i < iters; ++i) {
165              junit.textui.TestRunner.run(s);
# Line 117 | 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(new TestSuite(ForkJoinPoolTest.class));
222 <        suite.addTest(new TestSuite(ForkJoinTaskTest.class));
223 <        suite.addTest(new TestSuite(RecursiveActionTest.class));
224 <        suite.addTest(new TestSuite(RecursiveTaskTest.class));
225 <        suite.addTest(new TestSuite(LinkedTransferQueueTest.class));
226 <        suite.addTest(new TestSuite(PhaserTest.class));
227 <        suite.addTest(new TestSuite(ThreadLocalRandomTest.class));
228 <        suite.addTest(new TestSuite(AbstractExecutorServiceTest.class));
229 <        suite.addTest(new TestSuite(AbstractQueueTest.class));
230 <        suite.addTest(new TestSuite(AbstractQueuedSynchronizerTest.class));
231 <        suite.addTest(new TestSuite(AbstractQueuedLongSynchronizerTest.class));
232 <        suite.addTest(new TestSuite(ArrayBlockingQueueTest.class));
233 <        suite.addTest(new TestSuite(ArrayDequeTest.class));
234 <        suite.addTest(new TestSuite(AtomicBooleanTest.class));
235 <        suite.addTest(new TestSuite(AtomicIntegerArrayTest.class));
236 <        suite.addTest(new TestSuite(AtomicIntegerFieldUpdaterTest.class));
237 <        suite.addTest(new TestSuite(AtomicIntegerTest.class));
238 <        suite.addTest(new TestSuite(AtomicLongArrayTest.class));
239 <        suite.addTest(new TestSuite(AtomicLongFieldUpdaterTest.class));
240 <        suite.addTest(new TestSuite(AtomicLongTest.class));
241 <        suite.addTest(new TestSuite(AtomicMarkableReferenceTest.class));
242 <        suite.addTest(new TestSuite(AtomicReferenceArrayTest.class));
243 <        suite.addTest(new TestSuite(AtomicReferenceFieldUpdaterTest.class));
244 <        suite.addTest(new TestSuite(AtomicReferenceTest.class));
245 <        suite.addTest(new TestSuite(AtomicStampedReferenceTest.class));
246 <        suite.addTest(new TestSuite(ConcurrentHashMapTest.class));
247 <        suite.addTest(new TestSuite(ConcurrentLinkedDequeTest.class));
248 <        suite.addTest(new TestSuite(ConcurrentLinkedQueueTest.class));
249 <        suite.addTest(new TestSuite(ConcurrentSkipListMapTest.class));
250 <        suite.addTest(new TestSuite(ConcurrentSkipListSubMapTest.class));
251 <        suite.addTest(new TestSuite(ConcurrentSkipListSetTest.class));
252 <        suite.addTest(new TestSuite(ConcurrentSkipListSubSetTest.class));
253 <        suite.addTest(new TestSuite(CopyOnWriteArrayListTest.class));
254 <        suite.addTest(new TestSuite(CopyOnWriteArraySetTest.class));
255 <        suite.addTest(new TestSuite(CountDownLatchTest.class));
256 <        suite.addTest(new TestSuite(CyclicBarrierTest.class));
257 <        suite.addTest(new TestSuite(DelayQueueTest.class));
258 <        suite.addTest(new TestSuite(EntryTest.class));
259 <        suite.addTest(new TestSuite(ExchangerTest.class));
260 <        suite.addTest(new TestSuite(ExecutorsTest.class));
261 <        suite.addTest(new TestSuite(ExecutorCompletionServiceTest.class));
262 <        suite.addTest(new TestSuite(FutureTaskTest.class));
263 <        suite.addTest(new TestSuite(LinkedBlockingDequeTest.class));
264 <        suite.addTest(new TestSuite(LinkedBlockingQueueTest.class));
265 <        suite.addTest(new TestSuite(LinkedListTest.class));
266 <        suite.addTest(new TestSuite(LockSupportTest.class));
267 <        suite.addTest(new TestSuite(PriorityBlockingQueueTest.class));
268 <        suite.addTest(new TestSuite(PriorityQueueTest.class));
269 <        suite.addTest(new TestSuite(ReentrantLockTest.class));
270 <        suite.addTest(new TestSuite(ReentrantReadWriteLockTest.class));
271 <        suite.addTest(new TestSuite(ScheduledExecutorTest.class));
272 <        suite.addTest(new TestSuite(ScheduledExecutorSubclassTest.class));
273 <        suite.addTest(new TestSuite(SemaphoreTest.class));
274 <        suite.addTest(new TestSuite(SynchronousQueueTest.class));
275 <        suite.addTest(new TestSuite(SystemTest.class));
276 <        suite.addTest(new TestSuite(ThreadLocalTest.class));
277 <        suite.addTest(new TestSuite(ThreadPoolExecutorTest.class));
278 <        suite.addTest(new TestSuite(ThreadPoolExecutorSubclassTest.class));
279 <        suite.addTest(new TestSuite(ThreadTest.class));
280 <        suite.addTest(new TestSuite(TimeUnitTest.class));
281 <        suite.addTest(new TestSuite(TreeMapTest.class));
282 <        suite.addTest(new TestSuite(TreeSetTest.class));
283 <        suite.addTest(new TestSuite(TreeSubMapTest.class));
284 <        suite.addTest(new TestSuite(TreeSubSetTest.class));
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 >                "ForkJoinPool8Test",
291 >            };
292 >            addNamedTestClasses(suite, java8TestClassNames);
293 >        }
294  
295          return suite;
296      }
# Line 206 | Line 310 | public class JSR166TestCase extends Test
310          return 50;
311      }
312  
209
313      /**
314       * Sets delays as multiples of SHORT_DELAY.
315       */
# Line 214 | Line 317 | public class JSR166TestCase extends Test
317          SHORT_DELAY_MS = getShortDelay();
318          SMALL_DELAY_MS  = SHORT_DELAY_MS * 5;
319          MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
320 <        LONG_DELAY_MS   = SHORT_DELAY_MS * 50;
320 >        LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
321 >    }
322 >
323 >    /**
324 >     * Returns a timeout in milliseconds to be used in tests that
325 >     * verify that operations block or time out.
326 >     */
327 >    long timeoutMillis() {
328 >        return SHORT_DELAY_MS / 4;
329 >    }
330 >
331 >    /**
332 >     * Returns a new Date instance representing a time delayMillis
333 >     * milliseconds in the future.
334 >     */
335 >    Date delayedDate(long delayMillis) {
336 >        return new Date(System.currentTimeMillis() + delayMillis);
337      }
338  
339      /**
# Line 238 | Line 357 | public class JSR166TestCase extends Test
357      }
358  
359      /**
360 +     * Extra checks that get done for all test cases.
361 +     *
362       * Triggers test case failure if any thread assertions have failed,
363       * by rethrowing, in the test harness thread, any exception recorded
364       * earlier by threadRecordFailure.
365 +     *
366 +     * Triggers test case failure if interrupt status is set in the main thread.
367       */
368      public void tearDown() throws Exception {
369 <        Throwable t = threadFailure.get();
369 >        Throwable t = threadFailure.getAndSet(null);
370          if (t != null) {
371              if (t instanceof Error)
372                  throw (Error) t;
# Line 251 | Line 374 | public class JSR166TestCase extends Test
374                  throw (RuntimeException) t;
375              else if (t instanceof Exception)
376                  throw (Exception) t;
377 <            else
378 <                throw new AssertionError(t);
377 >            else {
378 >                AssertionFailedError afe =
379 >                    new AssertionFailedError(t.toString());
380 >                afe.initCause(t);
381 >                throw afe;
382 >            }
383          }
384 +
385 +        if (Thread.interrupted())
386 +            throw new AssertionFailedError("interrupt status set in main thread");
387      }
388  
389      /**
390       * Just like fail(reason), but additionally recording (using
391 <     * threadRecordFailure) any AssertionError thrown, so that the current
392 <     * testcase will fail.
391 >     * threadRecordFailure) any AssertionFailedError thrown, so that
392 >     * the current testcase will fail.
393       */
394      public void threadFail(String reason) {
395          try {
396              fail(reason);
397 <        } catch (Throwable t) {
397 >        } catch (AssertionFailedError t) {
398              threadRecordFailure(t);
399              fail(reason);
400          }
# Line 272 | Line 402 | public class JSR166TestCase extends Test
402  
403      /**
404       * Just like assertTrue(b), but additionally recording (using
405 <     * threadRecordFailure) any AssertionError thrown, so that the current
406 <     * testcase will fail.
405 >     * threadRecordFailure) any AssertionFailedError thrown, so that
406 >     * the current testcase will fail.
407       */
408      public void threadAssertTrue(boolean b) {
409          try {
410              assertTrue(b);
411 <        } catch (AssertionError t) {
411 >        } catch (AssertionFailedError t) {
412              threadRecordFailure(t);
413              throw t;
414          }
# Line 286 | Line 416 | public class JSR166TestCase extends Test
416  
417      /**
418       * Just like assertFalse(b), but additionally recording (using
419 <     * threadRecordFailure) any AssertionError thrown, so that the
420 <     * current testcase will fail.
419 >     * threadRecordFailure) any AssertionFailedError thrown, so that
420 >     * the current testcase will fail.
421       */
422      public void threadAssertFalse(boolean b) {
423          try {
424              assertFalse(b);
425 <        } catch (AssertionError t) {
425 >        } catch (AssertionFailedError t) {
426              threadRecordFailure(t);
427              throw t;
428          }
# Line 300 | Line 430 | public class JSR166TestCase extends Test
430  
431      /**
432       * Just like assertNull(x), but additionally recording (using
433 <     * threadRecordFailure) any AssertionError thrown, so that the
434 <     * current testcase will fail.
433 >     * threadRecordFailure) any AssertionFailedError thrown, so that
434 >     * the current testcase will fail.
435       */
436      public void threadAssertNull(Object x) {
437          try {
438              assertNull(x);
439 <        } catch (AssertionError t) {
439 >        } catch (AssertionFailedError t) {
440              threadRecordFailure(t);
441              throw t;
442          }
# Line 314 | Line 444 | public class JSR166TestCase extends Test
444  
445      /**
446       * Just like assertEquals(x, y), but additionally recording (using
447 <     * threadRecordFailure) any AssertionError thrown, so that the
448 <     * current testcase will fail.
447 >     * threadRecordFailure) any AssertionFailedError thrown, so that
448 >     * the current testcase will fail.
449       */
450      public void threadAssertEquals(long x, long y) {
451          try {
452              assertEquals(x, y);
453 <        } catch (AssertionError t) {
453 >        } catch (AssertionFailedError t) {
454              threadRecordFailure(t);
455              throw t;
456          }
# Line 328 | Line 458 | public class JSR166TestCase extends Test
458  
459      /**
460       * Just like assertEquals(x, y), but additionally recording (using
461 <     * threadRecordFailure) any AssertionError thrown, so that the
462 <     * current testcase will fail.
461 >     * threadRecordFailure) any AssertionFailedError thrown, so that
462 >     * the current testcase will fail.
463       */
464      public void threadAssertEquals(Object x, Object y) {
465          try {
466              assertEquals(x, y);
467 <        } catch (AssertionError t) {
467 >        } catch (AssertionFailedError t) {
468              threadRecordFailure(t);
469              throw t;
470 +        } catch (Throwable t) {
471 +            threadUnexpectedException(t);
472          }
473      }
474  
475      /**
476       * Just like assertSame(x, y), but additionally recording (using
477 <     * threadRecordFailure) any AssertionError thrown, so that the
478 <     * current testcase will fail.
477 >     * threadRecordFailure) any AssertionFailedError thrown, so that
478 >     * the current testcase will fail.
479       */
480      public void threadAssertSame(Object x, Object y) {
481          try {
482              assertSame(x, y);
483 <        } catch (AssertionError t) {
483 >        } catch (AssertionFailedError t) {
484              threadRecordFailure(t);
485              throw t;
486          }
# Line 369 | Line 501 | public class JSR166TestCase extends Test
501      }
502  
503      /**
504 <     * Calls threadFail with message "Unexpected exception" + ex.
504 >     * Records the given exception using {@link #threadRecordFailure},
505 >     * then rethrows the exception, wrapping it in an
506 >     * AssertionFailedError if necessary.
507       */
508      public void threadUnexpectedException(Throwable t) {
509          threadRecordFailure(t);
510          t.printStackTrace();
377        // Rethrow, wrapping in an AssertionError if necessary
511          if (t instanceof RuntimeException)
512              throw (RuntimeException) t;
513          else if (t instanceof Error)
514              throw (Error) t;
515          else {
516 <            AssertionError ae = new AssertionError("unexpected exception: " + t);
517 <            t.initCause(t);
518 <            throw ae;
519 <        }            
516 >            AssertionFailedError afe =
517 >                new AssertionFailedError("unexpected exception: " + t);
518 >            afe.initCause(t);
519 >            throw afe;
520 >        }
521 >    }
522 >
523 >    /**
524 >     * Delays, via Thread.sleep, for the given millisecond delay, but
525 >     * if the sleep is shorter than specified, may re-sleep or yield
526 >     * until time elapses.
527 >     */
528 >    static void delay(long millis) throws InterruptedException {
529 >        long startTime = System.nanoTime();
530 >        long ns = millis * 1000 * 1000;
531 >        for (;;) {
532 >            if (millis > 0L)
533 >                Thread.sleep(millis);
534 >            else // too short to sleep
535 >                Thread.yield();
536 >            long d = ns - (System.nanoTime() - startTime);
537 >            if (d > 0L)
538 >                millis = d / (1000 * 1000);
539 >            else
540 >                break;
541 >        }
542      }
543  
544      /**
545       * Waits out termination of a thread pool or fails doing so.
546       */
547 <    public void joinPool(ExecutorService exec) {
547 >    void joinPool(ExecutorService exec) {
548          try {
549              exec.shutdown();
550              assertTrue("ExecutorService did not terminate in a timely manner",
551 <                       exec.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
551 >                       exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS));
552          } catch (SecurityException ok) {
553              // Allowed in case test doesn't have privs
554          } catch (InterruptedException ie) {
# Line 401 | Line 556 | public class JSR166TestCase extends Test
556          }
557      }
558  
559 +    /**
560 +     * A debugging tool to print all stack traces, as jstack does.
561 +     */
562 +    static void printAllStackTraces() {
563 +        for (ThreadInfo info :
564 +                 ManagementFactory.getThreadMXBean()
565 +                 .dumpAllThreads(true, true))
566 +            System.err.print(info);
567 +    }
568 +
569 +    /**
570 +     * Checks that thread does not terminate within the default
571 +     * millisecond delay of {@code timeoutMillis()}.
572 +     */
573 +    void assertThreadStaysAlive(Thread thread) {
574 +        assertThreadStaysAlive(thread, timeoutMillis());
575 +    }
576 +
577 +    /**
578 +     * Checks that thread does not terminate within the given millisecond delay.
579 +     */
580 +    void assertThreadStaysAlive(Thread thread, long millis) {
581 +        try {
582 +            // No need to optimize the failing case via Thread.join.
583 +            delay(millis);
584 +            assertTrue(thread.isAlive());
585 +        } catch (InterruptedException ie) {
586 +            fail("Unexpected InterruptedException");
587 +        }
588 +    }
589 +
590 +    /**
591 +     * Checks that the threads do not terminate within the default
592 +     * millisecond delay of {@code timeoutMillis()}.
593 +     */
594 +    void assertThreadsStayAlive(Thread... threads) {
595 +        assertThreadsStayAlive(timeoutMillis(), threads);
596 +    }
597 +
598 +    /**
599 +     * Checks that the threads do not terminate within the given millisecond delay.
600 +     */
601 +    void assertThreadsStayAlive(long millis, Thread... threads) {
602 +        try {
603 +            // No need to optimize the failing case via Thread.join.
604 +            delay(millis);
605 +            for (Thread thread : threads)
606 +                assertTrue(thread.isAlive());
607 +        } catch (InterruptedException ie) {
608 +            fail("Unexpected InterruptedException");
609 +        }
610 +    }
611 +
612 +    /**
613 +     * Checks that future.get times out, with the default timeout of
614 +     * {@code timeoutMillis()}.
615 +     */
616 +    void assertFutureTimesOut(Future future) {
617 +        assertFutureTimesOut(future, timeoutMillis());
618 +    }
619 +
620 +    /**
621 +     * Checks that future.get times out, with the given millisecond timeout.
622 +     */
623 +    void assertFutureTimesOut(Future future, long timeoutMillis) {
624 +        long startTime = System.nanoTime();
625 +        try {
626 +            future.get(timeoutMillis, MILLISECONDS);
627 +            shouldThrow();
628 +        } catch (TimeoutException success) {
629 +        } catch (Exception e) {
630 +            threadUnexpectedException(e);
631 +        } finally { future.cancel(true); }
632 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
633 +    }
634  
635      /**
636       * Fails with message "should throw exception".
# Line 417 | Line 647 | public class JSR166TestCase extends Test
647      }
648  
649      /**
420     * Fails with message "Unexpected exception: " + ex.
421     */
422    public void unexpectedException(Throwable ex) {
423        ex.printStackTrace();
424        fail("Unexpected exception: " + ex);
425    }
426
427
428    /**
650       * The number of elements to place in collections, arrays, etc.
651       */
652      public static final int SIZE = 20;
# Line 462 | Line 683 | public class JSR166TestCase extends Test
683          SecurityManager sm = System.getSecurityManager();
684          if (sm == null) {
685              r.run();
686 +        }
687 +        runWithSecurityManagerWithPermissions(r, permissions);
688 +    }
689 +
690 +    /**
691 +     * Runs Runnable r with a security policy that permits precisely
692 +     * the specified permissions.  If there is no current security
693 +     * manager, a temporary one is set for the duration of the
694 +     * Runnable.  We require that any security manager permit
695 +     * getPolicy/setPolicy.
696 +     */
697 +    public void runWithSecurityManagerWithPermissions(Runnable r,
698 +                                                      Permission... permissions) {
699 +        SecurityManager sm = System.getSecurityManager();
700 +        if (sm == null) {
701              Policy savedPolicy = Policy.getPolicy();
702              try {
703                  Policy.setPolicy(permissivePolicy());
704                  System.setSecurityManager(new SecurityManager());
705 <                runWithPermissions(r, permissions);
705 >                runWithSecurityManagerWithPermissions(r, permissions);
706              } finally {
707                  System.setSecurityManager(null);
708                  Policy.setPolicy(savedPolicy);
# Line 514 | Line 750 | public class JSR166TestCase extends Test
750              return perms.implies(p);
751          }
752          public void refresh() {}
753 +        public String toString() {
754 +            List<Permission> ps = new ArrayList<Permission>();
755 +            for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
756 +                ps.add(e.nextElement());
757 +            return "AdjustablePolicy with permissions " + ps;
758 +        }
759      }
760  
761      /**
# Line 536 | Line 778 | public class JSR166TestCase extends Test
778      }
779  
780      /**
781 <     * Sleep until the timeout has elapsed, or interrupted.
782 <     * Does <em>NOT</em> throw InterruptedException.
781 >     * Sleeps until the given time has elapsed.
782 >     * Throws AssertionFailedError if interrupted.
783       */
784 <    void sleepTillInterrupted(long timeoutMillis) {
784 >    void sleep(long millis) {
785          try {
786 <            Thread.sleep(timeoutMillis);
787 <        } catch (InterruptedException wakeup) {}
786 >            delay(millis);
787 >        } catch (InterruptedException ie) {
788 >            AssertionFailedError afe =
789 >                new AssertionFailedError("Unexpected InterruptedException");
790 >            afe.initCause(ie);
791 >            throw afe;
792 >        }
793 >    }
794 >
795 >    /**
796 >     * Spin-waits up to the specified number of milliseconds for the given
797 >     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
798 >     */
799 >    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
800 >        long startTime = System.nanoTime();
801 >        for (;;) {
802 >            Thread.State s = thread.getState();
803 >            if (s == Thread.State.BLOCKED ||
804 >                s == Thread.State.WAITING ||
805 >                s == Thread.State.TIMED_WAITING)
806 >                return;
807 >            else if (s == Thread.State.TERMINATED)
808 >                fail("Unexpected thread termination");
809 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
810 >                threadAssertTrue(thread.isAlive());
811 >                return;
812 >            }
813 >            Thread.yield();
814 >        }
815      }
816  
817      /**
818 <     * Returns a new started Thread running the given runnable.
818 >     * Waits up to LONG_DELAY_MS for the given thread to enter a wait
819 >     * state: BLOCKED, WAITING, or TIMED_WAITING.
820 >     */
821 >    void waitForThreadToEnterWaitState(Thread thread) {
822 >        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
823 >    }
824 >
825 >    /**
826 >     * Returns the number of milliseconds since time given by
827 >     * startNanoTime, which must have been previously returned from a
828 >     * call to {@link System.nanoTime()}.
829 >     */
830 >    long millisElapsedSince(long startNanoTime) {
831 >        return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
832 >    }
833 >
834 >    /**
835 >     * Returns a new started daemon Thread running the given runnable.
836       */
837      Thread newStartedThread(Runnable runnable) {
838          Thread t = new Thread(runnable);
839 +        t.setDaemon(true);
840          t.start();
841          return t;
842      }
843  
844 +    /**
845 +     * Waits for the specified time (in milliseconds) for the thread
846 +     * to terminate (using {@link Thread#join(long)}), else interrupts
847 +     * the thread (in the hope that it may terminate later) and fails.
848 +     */
849 +    void awaitTermination(Thread t, long timeoutMillis) {
850 +        try {
851 +            t.join(timeoutMillis);
852 +        } catch (InterruptedException ie) {
853 +            threadUnexpectedException(ie);
854 +        } finally {
855 +            if (t.getState() != Thread.State.TERMINATED) {
856 +                t.interrupt();
857 +                fail("Test timed out");
858 +            }
859 +        }
860 +    }
861 +
862 +    /**
863 +     * Waits for LONG_DELAY_MS milliseconds for the thread to
864 +     * terminate (using {@link Thread#join(long)}), else interrupts
865 +     * the thread (in the hope that it may terminate later) and fails.
866 +     */
867 +    void awaitTermination(Thread t) {
868 +        awaitTermination(t, LONG_DELAY_MS);
869 +    }
870 +
871      // Some convenient Runnable classes
872  
873      public abstract class CheckedRunnable implements Runnable {
# Line 616 | Line 930 | public class JSR166TestCase extends Test
930                  realRun();
931                  threadShouldThrow("InterruptedException");
932              } catch (InterruptedException success) {
933 +                threadAssertFalse(Thread.interrupted());
934              } catch (Throwable t) {
935                  threadUnexpectedException(t);
936              }
# Line 645 | Line 960 | public class JSR166TestCase extends Test
960                  threadShouldThrow("InterruptedException");
961                  return result;
962              } catch (InterruptedException success) {
963 +                threadAssertFalse(Thread.interrupted());
964              } catch (Throwable t) {
965                  threadUnexpectedException(t);
966              }
# Line 668 | Line 984 | public class JSR166TestCase extends Test
984  
985      public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
986          return new CheckedCallable<String>() {
987 <            public String realCall() {
987 >            protected String realCall() {
988                  try {
989                      latch.await();
990                  } catch (InterruptedException quittingTime) {}
# Line 676 | Line 992 | public class JSR166TestCase extends Test
992              }};
993      }
994  
995 +    public Runnable awaiter(final CountDownLatch latch) {
996 +        return new CheckedRunnable() {
997 +            public void realRun() throws InterruptedException {
998 +                await(latch);
999 +            }};
1000 +    }
1001 +
1002 +    public void await(CountDownLatch latch) {
1003 +        try {
1004 +            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1005 +        } catch (Throwable t) {
1006 +            threadUnexpectedException(t);
1007 +        }
1008 +    }
1009 +
1010 +    public void await(Semaphore semaphore) {
1011 +        try {
1012 +            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1013 +        } catch (Throwable t) {
1014 +            threadUnexpectedException(t);
1015 +        }
1016 +    }
1017 +
1018 + //     /**
1019 + //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1020 + //      */
1021 + //     public void await(AtomicBoolean flag) {
1022 + //         await(flag, LONG_DELAY_MS);
1023 + //     }
1024 +
1025 + //     /**
1026 + //      * Spin-waits up to the specified timeout until flag becomes true.
1027 + //      */
1028 + //     public void await(AtomicBoolean flag, long timeoutMillis) {
1029 + //         long startTime = System.nanoTime();
1030 + //         while (!flag.get()) {
1031 + //             if (millisElapsedSince(startTime) > timeoutMillis)
1032 + //                 throw new AssertionFailedError("timed out");
1033 + //             Thread.yield();
1034 + //         }
1035 + //     }
1036 +
1037      public static class NPETask implements Callable<String> {
1038          public String call() { throw new NullPointerException(); }
1039      }
# Line 686 | Line 1044 | public class JSR166TestCase extends Test
1044  
1045      public class ShortRunnable extends CheckedRunnable {
1046          protected void realRun() throws Throwable {
1047 <            Thread.sleep(SHORT_DELAY_MS);
1047 >            delay(SHORT_DELAY_MS);
1048          }
1049      }
1050  
1051      public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1052          protected void realRun() throws InterruptedException {
1053 <            Thread.sleep(SHORT_DELAY_MS);
1053 >            delay(SHORT_DELAY_MS);
1054          }
1055      }
1056  
1057      public class SmallRunnable extends CheckedRunnable {
1058          protected void realRun() throws Throwable {
1059 <            Thread.sleep(SMALL_DELAY_MS);
1059 >            delay(SMALL_DELAY_MS);
1060          }
1061      }
1062  
1063      public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1064          protected void realRun() {
1065              try {
1066 <                Thread.sleep(SMALL_DELAY_MS);
1066 >                delay(SMALL_DELAY_MS);
1067              } catch (InterruptedException ok) {}
1068          }
1069      }
1070  
1071      public class SmallCallable extends CheckedCallable {
1072          protected Object realCall() throws InterruptedException {
1073 <            Thread.sleep(SMALL_DELAY_MS);
1073 >            delay(SMALL_DELAY_MS);
1074              return Boolean.TRUE;
1075          }
1076      }
1077  
720    public class SmallInterruptedRunnable extends CheckedInterruptedRunnable {
721        protected void realRun() throws InterruptedException {
722            Thread.sleep(SMALL_DELAY_MS);
723        }
724    }
725
1078      public class MediumRunnable extends CheckedRunnable {
1079          protected void realRun() throws Throwable {
1080 <            Thread.sleep(MEDIUM_DELAY_MS);
1080 >            delay(MEDIUM_DELAY_MS);
1081          }
1082      }
1083  
1084      public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1085          protected void realRun() throws InterruptedException {
1086 <            Thread.sleep(MEDIUM_DELAY_MS);
1086 >            delay(MEDIUM_DELAY_MS);
1087          }
1088      }
1089  
1090 +    public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1091 +        return new CheckedRunnable() {
1092 +            protected void realRun() {
1093 +                try {
1094 +                    delay(timeoutMillis);
1095 +                } catch (InterruptedException ok) {}
1096 +            }};
1097 +    }
1098 +
1099      public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1100          protected void realRun() {
1101              try {
1102 <                Thread.sleep(MEDIUM_DELAY_MS);
1102 >                delay(MEDIUM_DELAY_MS);
1103              } catch (InterruptedException ok) {}
1104          }
1105      }
# Line 746 | Line 1107 | public class JSR166TestCase extends Test
1107      public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1108          protected void realRun() {
1109              try {
1110 <                Thread.sleep(LONG_DELAY_MS);
1110 >                delay(LONG_DELAY_MS);
1111              } catch (InterruptedException ok) {}
1112          }
1113      }
# Line 760 | Line 1121 | public class JSR166TestCase extends Test
1121          }
1122      }
1123  
1124 +    public interface TrackedRunnable extends Runnable {
1125 +        boolean isDone();
1126 +    }
1127 +
1128 +    public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
1129 +        return new TrackedRunnable() {
1130 +                private volatile boolean done = false;
1131 +                public boolean isDone() { return done; }
1132 +                public void run() {
1133 +                    try {
1134 +                        delay(timeoutMillis);
1135 +                        done = true;
1136 +                    } catch (InterruptedException ok) {}
1137 +                }
1138 +            };
1139 +    }
1140 +
1141      public static class TrackedShortRunnable implements Runnable {
1142          public volatile boolean done = false;
1143          public void run() {
1144              try {
1145 <                Thread.sleep(SMALL_DELAY_MS);
1145 >                delay(SHORT_DELAY_MS);
1146 >                done = true;
1147 >            } catch (InterruptedException ok) {}
1148 >        }
1149 >    }
1150 >
1151 >    public static class TrackedSmallRunnable implements Runnable {
1152 >        public volatile boolean done = false;
1153 >        public void run() {
1154 >            try {
1155 >                delay(SMALL_DELAY_MS);
1156                  done = true;
1157              } catch (InterruptedException ok) {}
1158          }
# Line 774 | Line 1162 | public class JSR166TestCase extends Test
1162          public volatile boolean done = false;
1163          public void run() {
1164              try {
1165 <                Thread.sleep(MEDIUM_DELAY_MS);
1165 >                delay(MEDIUM_DELAY_MS);
1166                  done = true;
1167              } catch (InterruptedException ok) {}
1168          }
# Line 784 | Line 1172 | public class JSR166TestCase extends Test
1172          public volatile boolean done = false;
1173          public void run() {
1174              try {
1175 <                Thread.sleep(LONG_DELAY_MS);
1175 >                delay(LONG_DELAY_MS);
1176                  done = true;
1177              } catch (InterruptedException ok) {}
1178          }
# Line 801 | Line 1189 | public class JSR166TestCase extends Test
1189          public volatile boolean done = false;
1190          public Object call() {
1191              try {
1192 <                Thread.sleep(SMALL_DELAY_MS);
1192 >                delay(SMALL_DELAY_MS);
1193                  done = true;
1194              } catch (InterruptedException ok) {}
1195              return Boolean.TRUE;
# Line 847 | Line 1235 | public class JSR166TestCase extends Test
1235                                        ThreadPoolExecutor executor) {}
1236      }
1237  
1238 +    /**
1239 +     * A CyclicBarrier that uses timed await and fails with
1240 +     * AssertionFailedErrors instead of throwing checked exceptions.
1241 +     */
1242 +    public class CheckedBarrier extends CyclicBarrier {
1243 +        public CheckedBarrier(int parties) { super(parties); }
1244 +
1245 +        public int await() {
1246 +            try {
1247 +                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1248 +            } catch (TimeoutException e) {
1249 +                throw new AssertionFailedError("timed out");
1250 +            } catch (Exception e) {
1251 +                AssertionFailedError afe =
1252 +                    new AssertionFailedError("Unexpected exception: " + e);
1253 +                afe.initCause(e);
1254 +                throw afe;
1255 +            }
1256 +        }
1257 +    }
1258 +
1259 +    void checkEmpty(BlockingQueue q) {
1260 +        try {
1261 +            assertTrue(q.isEmpty());
1262 +            assertEquals(0, q.size());
1263 +            assertNull(q.peek());
1264 +            assertNull(q.poll());
1265 +            assertNull(q.poll(0, MILLISECONDS));
1266 +            assertEquals(q.toString(), "[]");
1267 +            assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1268 +            assertFalse(q.iterator().hasNext());
1269 +            try {
1270 +                q.element();
1271 +                shouldThrow();
1272 +            } catch (NoSuchElementException success) {}
1273 +            try {
1274 +                q.iterator().next();
1275 +                shouldThrow();
1276 +            } catch (NoSuchElementException success) {}
1277 +            try {
1278 +                q.remove();
1279 +                shouldThrow();
1280 +            } catch (NoSuchElementException success) {}
1281 +        } catch (InterruptedException ie) {
1282 +            threadUnexpectedException(ie);
1283 +        }
1284 +    }
1285 +
1286 +    void assertSerialEquals(Object x, Object y) {
1287 +        assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1288 +    }
1289 +
1290 +    void assertNotSerialEquals(Object x, Object y) {
1291 +        assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1292 +    }
1293 +
1294 +    byte[] serialBytes(Object o) {
1295 +        try {
1296 +            ByteArrayOutputStream bos = new ByteArrayOutputStream();
1297 +            ObjectOutputStream oos = new ObjectOutputStream(bos);
1298 +            oos.writeObject(o);
1299 +            oos.flush();
1300 +            oos.close();
1301 +            return bos.toByteArray();
1302 +        } catch (Throwable t) {
1303 +            threadUnexpectedException(t);
1304 +            return new byte[0];
1305 +        }
1306 +    }
1307 +
1308 +    @SuppressWarnings("unchecked")
1309 +    <T> T serialClone(T o) {
1310 +        try {
1311 +            ObjectInputStream ois = new ObjectInputStream
1312 +                (new ByteArrayInputStream(serialBytes(o)));
1313 +            T clone = (T) ois.readObject();
1314 +            assertSame(o.getClass(), clone.getClass());
1315 +            return clone;
1316 +        } catch (Throwable t) {
1317 +            threadUnexpectedException(t);
1318 +            return null;
1319 +        }
1320 +    }
1321   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines