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.52 by jsr166, Mon Sep 13 23:19:31 2010 UTC vs.
Revision 1.93 by jsr166, Sun Dec 16 17:22:42 2012 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.util.*;
10 > import java.io.ByteArrayInputStream;
11 > import java.io.ByteArrayOutputStream;
12 > import java.io.ObjectInputStream;
13 > import java.io.ObjectOutputStream;
14 > import java.util.ArrayList;
15 > import java.util.Arrays;
16 > import java.util.Date;
17 > import java.util.Enumeration;
18 > import java.util.List;
19 > import java.util.NoSuchElementException;
20 > import java.util.PropertyPermission;
21   import java.util.concurrent.*;
22 + import java.util.concurrent.atomic.AtomicBoolean;
23 + import java.util.concurrent.atomic.AtomicReference;
24   import static java.util.concurrent.TimeUnit.MILLISECONDS;
25 < import java.io.*;
26 < import java.security.*;
25 > import static java.util.concurrent.TimeUnit.NANOSECONDS;
26 > import java.security.CodeSource;
27 > import java.security.Permission;
28 > import java.security.PermissionCollection;
29 > import java.security.Permissions;
30 > import java.security.Policy;
31 > import java.security.ProtectionDomain;
32 > import java.security.SecurityPermission;
33  
34   /**
35   * Base class for JSR166 Junit TCK tests.  Defines some constants,
# Line 54 | Line 72 | import java.security.*;
72   *
73   * </ol>
74   *
75 < * <p> <b>Other notes</b>
75 > * <p><b>Other notes</b>
76   * <ul>
77   *
78   * <li> Usually, there is one testcase method per JSR166 method
# Line 90 | Line 108 | public class JSR166TestCase extends Test
108      private static final boolean useSecurityManager =
109          Boolean.getBoolean("jsr166.useSecurityManager");
110  
111 +    protected static final boolean expensiveTests =
112 +        Boolean.getBoolean("jsr166.expensiveTests");
113 +
114 +    /**
115 +     * If true, report on stdout all "slow" tests, that is, ones that
116 +     * take more than profileThreshold milliseconds to execute.
117 +     */
118 +    private static final boolean profileTests =
119 +        Boolean.getBoolean("jsr166.profileTests");
120 +
121 +    /**
122 +     * The number of milliseconds that tests are permitted for
123 +     * execution without being reported, when profileTests is set.
124 +     */
125 +    private static final long profileThreshold =
126 +        Long.getLong("jsr166.profileThreshold", 100);
127 +
128 +    protected void runTest() throws Throwable {
129 +        if (profileTests)
130 +            runTestProfiled();
131 +        else
132 +            super.runTest();
133 +    }
134 +
135 +    protected void runTestProfiled() throws Throwable {
136 +        long t0 = System.nanoTime();
137 +        try {
138 +            super.runTest();
139 +        } finally {
140 +            long elapsedMillis =
141 +                (System.nanoTime() - t0) / (1000L * 1000L);
142 +            if (elapsedMillis >= profileThreshold)
143 +                System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
144 +        }
145 +    }
146 +
147      /**
148       * Runs all JSR166 unit tests using junit.textui.TestRunner
149       */
# Line 99 | Line 153 | public class JSR166TestCase extends Test
153              Policy.setPolicy(permissivePolicy());
154              System.setSecurityManager(new SecurityManager());
155          }
156 <        int iters = 1;
157 <        if (args.length > 0)
104 <            iters = Integer.parseInt(args[0]);
156 >        int iters = (args.length == 0) ? 1 : Integer.parseInt(args[0]);
157 >
158          Test s = suite();
159          for (int i = 0; i < iters; ++i) {
160              junit.textui.TestRunner.run(s);
# Line 111 | Line 164 | public class JSR166TestCase extends Test
164          System.exit(0);
165      }
166  
167 +    public static TestSuite newTestSuite(Object... suiteOrClasses) {
168 +        TestSuite suite = new TestSuite();
169 +        for (Object suiteOrClass : suiteOrClasses) {
170 +            if (suiteOrClass instanceof TestSuite)
171 +                suite.addTest((TestSuite) suiteOrClass);
172 +            else if (suiteOrClass instanceof Class)
173 +                suite.addTest(new TestSuite((Class<?>) suiteOrClass));
174 +            else
175 +                throw new ClassCastException("not a test suite or class");
176 +        }
177 +        return suite;
178 +    }
179 +
180      /**
181 <     * Collects all JSR166 unit tests as one suite
181 >     * Collects all JSR166 unit tests as one suite.
182       */
183      public static Test suite() {
184 <        TestSuite suite = new TestSuite("JSR166 Unit Tests");
185 <
186 <        suite.addTest(new TestSuite(ForkJoinPoolTest.class));
187 <        suite.addTest(new TestSuite(ForkJoinTaskTest.class));
188 <        suite.addTest(new TestSuite(RecursiveActionTest.class));
189 <        suite.addTest(new TestSuite(RecursiveTaskTest.class));
190 <        suite.addTest(new TestSuite(LinkedTransferQueueTest.class));
191 <        suite.addTest(new TestSuite(PhaserTest.class));
192 <        suite.addTest(new TestSuite(ThreadLocalRandomTest.class));
193 <        suite.addTest(new TestSuite(AbstractExecutorServiceTest.class));
194 <        suite.addTest(new TestSuite(AbstractQueueTest.class));
195 <        suite.addTest(new TestSuite(AbstractQueuedSynchronizerTest.class));
196 <        suite.addTest(new TestSuite(AbstractQueuedLongSynchronizerTest.class));
197 <        suite.addTest(new TestSuite(ArrayBlockingQueueTest.class));
198 <        suite.addTest(new TestSuite(ArrayDequeTest.class));
199 <        suite.addTest(new TestSuite(AtomicBooleanTest.class));
200 <        suite.addTest(new TestSuite(AtomicIntegerArrayTest.class));
201 <        suite.addTest(new TestSuite(AtomicIntegerFieldUpdaterTest.class));
202 <        suite.addTest(new TestSuite(AtomicIntegerTest.class));
203 <        suite.addTest(new TestSuite(AtomicLongArrayTest.class));
204 <        suite.addTest(new TestSuite(AtomicLongFieldUpdaterTest.class));
205 <        suite.addTest(new TestSuite(AtomicLongTest.class));
206 <        suite.addTest(new TestSuite(AtomicMarkableReferenceTest.class));
207 <        suite.addTest(new TestSuite(AtomicReferenceArrayTest.class));
208 <        suite.addTest(new TestSuite(AtomicReferenceFieldUpdaterTest.class));
209 <        suite.addTest(new TestSuite(AtomicReferenceTest.class));
210 <        suite.addTest(new TestSuite(AtomicStampedReferenceTest.class));
211 <        suite.addTest(new TestSuite(ConcurrentHashMapTest.class));
212 <        suite.addTest(new TestSuite(ConcurrentLinkedDequeTest.class));
213 <        suite.addTest(new TestSuite(ConcurrentLinkedQueueTest.class));
214 <        suite.addTest(new TestSuite(ConcurrentSkipListMapTest.class));
215 <        suite.addTest(new TestSuite(ConcurrentSkipListSubMapTest.class));
216 <        suite.addTest(new TestSuite(ConcurrentSkipListSetTest.class));
217 <        suite.addTest(new TestSuite(ConcurrentSkipListSubSetTest.class));
218 <        suite.addTest(new TestSuite(CopyOnWriteArrayListTest.class));
219 <        suite.addTest(new TestSuite(CopyOnWriteArraySetTest.class));
220 <        suite.addTest(new TestSuite(CountDownLatchTest.class));
221 <        suite.addTest(new TestSuite(CyclicBarrierTest.class));
222 <        suite.addTest(new TestSuite(DelayQueueTest.class));
223 <        suite.addTest(new TestSuite(EntryTest.class));
224 <        suite.addTest(new TestSuite(ExchangerTest.class));
225 <        suite.addTest(new TestSuite(ExecutorsTest.class));
226 <        suite.addTest(new TestSuite(ExecutorCompletionServiceTest.class));
227 <        suite.addTest(new TestSuite(FutureTaskTest.class));
228 <        suite.addTest(new TestSuite(LinkedBlockingDequeTest.class));
229 <        suite.addTest(new TestSuite(LinkedBlockingQueueTest.class));
230 <        suite.addTest(new TestSuite(LinkedListTest.class));
231 <        suite.addTest(new TestSuite(LockSupportTest.class));
232 <        suite.addTest(new TestSuite(PriorityBlockingQueueTest.class));
233 <        suite.addTest(new TestSuite(PriorityQueueTest.class));
234 <        suite.addTest(new TestSuite(ReentrantLockTest.class));
235 <        suite.addTest(new TestSuite(ReentrantReadWriteLockTest.class));
236 <        suite.addTest(new TestSuite(ScheduledExecutorTest.class));
237 <        suite.addTest(new TestSuite(ScheduledExecutorSubclassTest.class));
238 <        suite.addTest(new TestSuite(SemaphoreTest.class));
239 <        suite.addTest(new TestSuite(SynchronousQueueTest.class));
240 <        suite.addTest(new TestSuite(SystemTest.class));
241 <        suite.addTest(new TestSuite(ThreadLocalTest.class));
242 <        suite.addTest(new TestSuite(ThreadPoolExecutorTest.class));
243 <        suite.addTest(new TestSuite(ThreadPoolExecutorSubclassTest.class));
244 <        suite.addTest(new TestSuite(ThreadTest.class));
245 <        suite.addTest(new TestSuite(TimeUnitTest.class));
246 <        suite.addTest(new TestSuite(TreeMapTest.class));
247 <        suite.addTest(new TestSuite(TreeSetTest.class));
248 <        suite.addTest(new TestSuite(TreeSubMapTest.class));
183 <        suite.addTest(new TestSuite(TreeSubSetTest.class));
184 <
185 <        return suite;
184 >        return newTestSuite(
185 >            ForkJoinPoolTest.suite(),
186 >            ForkJoinTaskTest.suite(),
187 >            RecursiveActionTest.suite(),
188 >            RecursiveTaskTest.suite(),
189 >            LinkedTransferQueueTest.suite(),
190 >            PhaserTest.suite(),
191 >            ThreadLocalRandomTest.suite(),
192 >            AbstractExecutorServiceTest.suite(),
193 >            AbstractQueueTest.suite(),
194 >            AbstractQueuedSynchronizerTest.suite(),
195 >            AbstractQueuedLongSynchronizerTest.suite(),
196 >            ArrayBlockingQueueTest.suite(),
197 >            ArrayDequeTest.suite(),
198 >            AtomicBooleanTest.suite(),
199 >            AtomicIntegerArrayTest.suite(),
200 >            AtomicIntegerFieldUpdaterTest.suite(),
201 >            AtomicIntegerTest.suite(),
202 >            AtomicLongArrayTest.suite(),
203 >            AtomicLongFieldUpdaterTest.suite(),
204 >            AtomicLongTest.suite(),
205 >            AtomicMarkableReferenceTest.suite(),
206 >            AtomicReferenceArrayTest.suite(),
207 >            AtomicReferenceFieldUpdaterTest.suite(),
208 >            AtomicReferenceTest.suite(),
209 >            AtomicStampedReferenceTest.suite(),
210 >            ConcurrentHashMapTest.suite(),
211 >            ConcurrentLinkedDequeTest.suite(),
212 >            ConcurrentLinkedQueueTest.suite(),
213 >            ConcurrentSkipListMapTest.suite(),
214 >            ConcurrentSkipListSubMapTest.suite(),
215 >            ConcurrentSkipListSetTest.suite(),
216 >            ConcurrentSkipListSubSetTest.suite(),
217 >            CopyOnWriteArrayListTest.suite(),
218 >            CopyOnWriteArraySetTest.suite(),
219 >            CountDownLatchTest.suite(),
220 >            CyclicBarrierTest.suite(),
221 >            DelayQueueTest.suite(),
222 >            EntryTest.suite(),
223 >            ExchangerTest.suite(),
224 >            ExecutorsTest.suite(),
225 >            ExecutorCompletionServiceTest.suite(),
226 >            FutureTaskTest.suite(),
227 >            LinkedBlockingDequeTest.suite(),
228 >            LinkedBlockingQueueTest.suite(),
229 >            LinkedListTest.suite(),
230 >            LockSupportTest.suite(),
231 >            PriorityBlockingQueueTest.suite(),
232 >            PriorityQueueTest.suite(),
233 >            ReentrantLockTest.suite(),
234 >            ReentrantReadWriteLockTest.suite(),
235 >            ScheduledExecutorTest.suite(),
236 >            ScheduledExecutorSubclassTest.suite(),
237 >            SemaphoreTest.suite(),
238 >            SynchronousQueueTest.suite(),
239 >            SystemTest.suite(),
240 >            ThreadLocalTest.suite(),
241 >            ThreadPoolExecutorTest.suite(),
242 >            ThreadPoolExecutorSubclassTest.suite(),
243 >            ThreadTest.suite(),
244 >            TimeUnitTest.suite(),
245 >            TreeMapTest.suite(),
246 >            TreeSetTest.suite(),
247 >            TreeSubMapTest.suite(),
248 >            TreeSubSetTest.suite());
249      }
250  
251  
# Line 200 | Line 263 | public class JSR166TestCase extends Test
263          return 50;
264      }
265  
203
266      /**
267       * Sets delays as multiples of SHORT_DELAY.
268       */
269      protected void setDelays() {
270          SHORT_DELAY_MS = getShortDelay();
271 <        SMALL_DELAY_MS = SHORT_DELAY_MS * 5;
271 >        SMALL_DELAY_MS  = SHORT_DELAY_MS * 5;
272          MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
273 <        LONG_DELAY_MS = SHORT_DELAY_MS * 50;
273 >        LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
274      }
275  
276      /**
277 <     * Flag set true if any threadAssert methods fail
277 >     * Returns a timeout in milliseconds to be used in tests that
278 >     * verify that operations block or time out.
279       */
280 <    volatile boolean threadFailed;
280 >    long timeoutMillis() {
281 >        return SHORT_DELAY_MS / 4;
282 >    }
283  
284      /**
285 <     * Initializes test to indicate that no thread assertions have failed
285 >     * Returns a new Date instance representing a time delayMillis
286 >     * milliseconds in the future.
287       */
288 +    Date delayedDate(long delayMillis) {
289 +        return new Date(System.currentTimeMillis() + delayMillis);
290 +    }
291 +
292 +    /**
293 +     * The first exception encountered if any threadAssertXXX method fails.
294 +     */
295 +    private final AtomicReference<Throwable> threadFailure
296 +        = new AtomicReference<Throwable>(null);
297 +
298 +    /**
299 +     * Records an exception so that it can be rethrown later in the test
300 +     * harness thread, triggering a test case failure.  Only the first
301 +     * failure is recorded; subsequent calls to this method from within
302 +     * the same test have no effect.
303 +     */
304 +    public void threadRecordFailure(Throwable t) {
305 +        threadFailure.compareAndSet(null, t);
306 +    }
307 +
308      public void setUp() {
309          setDelays();
224        threadFailed = false;
310      }
311  
312      /**
313 <     * Triggers test case failure if any thread assertions have failed
314 <     */
315 <    public void tearDown() {
316 <        assertFalse(threadFailed);
313 >     * Extra checks that get done for all test cases.
314 >     *
315 >     * Triggers test case failure if any thread assertions have failed,
316 >     * by rethrowing, in the test harness thread, any exception recorded
317 >     * earlier by threadRecordFailure.
318 >     *
319 >     * Triggers test case failure if interrupt status is set in the main thread.
320 >     */
321 >    public void tearDown() throws Exception {
322 >        Throwable t = threadFailure.getAndSet(null);
323 >        if (t != null) {
324 >            if (t instanceof Error)
325 >                throw (Error) t;
326 >            else if (t instanceof RuntimeException)
327 >                throw (RuntimeException) t;
328 >            else if (t instanceof Exception)
329 >                throw (Exception) t;
330 >            else {
331 >                AssertionFailedError afe =
332 >                    new AssertionFailedError(t.toString());
333 >                afe.initCause(t);
334 >                throw afe;
335 >            }
336 >        }
337 >
338 >        if (Thread.interrupted())
339 >            throw new AssertionFailedError("interrupt status set in main thread");
340      }
341  
342      /**
343 <     * Fail, also setting status to indicate current testcase should fail
343 >     * Just like fail(reason), but additionally recording (using
344 >     * threadRecordFailure) any AssertionFailedError thrown, so that
345 >     * the current testcase will fail.
346       */
347      public void threadFail(String reason) {
348 <        threadFailed = true;
349 <        fail(reason);
348 >        try {
349 >            fail(reason);
350 >        } catch (AssertionFailedError t) {
351 >            threadRecordFailure(t);
352 >            fail(reason);
353 >        }
354      }
355  
356      /**
357 <     * If expression not true, set status to indicate current testcase
358 <     * should fail
357 >     * Just like assertTrue(b), but additionally recording (using
358 >     * threadRecordFailure) any AssertionFailedError thrown, so that
359 >     * the current testcase will fail.
360       */
361      public void threadAssertTrue(boolean b) {
362 <        if (!b) {
248 <            threadFailed = true;
362 >        try {
363              assertTrue(b);
364 +        } catch (AssertionFailedError t) {
365 +            threadRecordFailure(t);
366 +            throw t;
367          }
368      }
369  
370      /**
371 <     * If expression not false, set status to indicate current testcase
372 <     * should fail
371 >     * Just like assertFalse(b), but additionally recording (using
372 >     * threadRecordFailure) any AssertionFailedError thrown, so that
373 >     * the current testcase will fail.
374       */
375      public void threadAssertFalse(boolean b) {
376 <        if (b) {
259 <            threadFailed = true;
376 >        try {
377              assertFalse(b);
378 +        } catch (AssertionFailedError t) {
379 +            threadRecordFailure(t);
380 +            throw t;
381          }
382      }
383  
384      /**
385 <     * If argument not null, set status to indicate current testcase
386 <     * should fail
385 >     * Just like assertNull(x), but additionally recording (using
386 >     * threadRecordFailure) any AssertionFailedError thrown, so that
387 >     * the current testcase will fail.
388       */
389      public void threadAssertNull(Object x) {
390 <        if (x != null) {
270 <            threadFailed = true;
390 >        try {
391              assertNull(x);
392 +        } catch (AssertionFailedError t) {
393 +            threadRecordFailure(t);
394 +            throw t;
395          }
396      }
397  
398      /**
399 <     * If arguments not equal, set status to indicate current testcase
400 <     * should fail
399 >     * Just like assertEquals(x, y), but additionally recording (using
400 >     * threadRecordFailure) any AssertionFailedError thrown, so that
401 >     * the current testcase will fail.
402       */
403      public void threadAssertEquals(long x, long y) {
404 <        if (x != y) {
281 <            threadFailed = true;
404 >        try {
405              assertEquals(x, y);
406 +        } catch (AssertionFailedError t) {
407 +            threadRecordFailure(t);
408 +            throw t;
409          }
410      }
411  
412      /**
413 <     * If arguments not equal, set status to indicate current testcase
414 <     * should fail
413 >     * Just like assertEquals(x, y), but additionally recording (using
414 >     * threadRecordFailure) any AssertionFailedError thrown, so that
415 >     * the current testcase will fail.
416       */
417      public void threadAssertEquals(Object x, Object y) {
418 <        if (x != y && (x == null || !x.equals(y))) {
292 <            threadFailed = true;
418 >        try {
419              assertEquals(x, y);
420 +        } catch (AssertionFailedError t) {
421 +            threadRecordFailure(t);
422 +            throw t;
423 +        } catch (Throwable t) {
424 +            threadUnexpectedException(t);
425          }
426      }
427  
428      /**
429 <     * If arguments not identical, set status to indicate current testcase
430 <     * should fail
429 >     * Just like assertSame(x, y), but additionally recording (using
430 >     * threadRecordFailure) any AssertionFailedError thrown, so that
431 >     * the current testcase will fail.
432       */
433      public void threadAssertSame(Object x, Object y) {
434 <        if (x != y) {
303 <            threadFailed = true;
434 >        try {
435              assertSame(x, y);
436 +        } catch (AssertionFailedError t) {
437 +            threadRecordFailure(t);
438 +            throw t;
439          }
440      }
441  
442      /**
443 <     * threadFail with message "should throw exception"
443 >     * Calls threadFail with message "should throw exception".
444       */
445      public void threadShouldThrow() {
446 <        threadFailed = true;
313 <        fail("should throw exception");
446 >        threadFail("should throw exception");
447      }
448  
449      /**
450 <     * threadFail with message "should throw" + exceptionName
450 >     * Calls threadFail with message "should throw" + exceptionName.
451       */
452      public void threadShouldThrow(String exceptionName) {
453 <        threadFailed = true;
321 <        fail("should throw " + exceptionName);
453 >        threadFail("should throw " + exceptionName);
454      }
455  
456      /**
457 <     * threadFail with message "Unexpected exception"
457 >     * Records the given exception using {@link #threadRecordFailure},
458 >     * then rethrows the exception, wrapping it in an
459 >     * AssertionFailedError if necessary.
460       */
461 <    public void threadUnexpectedException() {
462 <        threadFailed = true;
463 <        fail("Unexpected exception");
461 >    public void threadUnexpectedException(Throwable t) {
462 >        threadRecordFailure(t);
463 >        t.printStackTrace();
464 >        if (t instanceof RuntimeException)
465 >            throw (RuntimeException) t;
466 >        else if (t instanceof Error)
467 >            throw (Error) t;
468 >        else {
469 >            AssertionFailedError afe =
470 >                new AssertionFailedError("unexpected exception: " + t);
471 >            afe.initCause(t);
472 >            throw afe;
473 >        }
474      }
475  
476      /**
477 <     * threadFail with message "Unexpected exception", with argument
477 >     * Delays, via Thread.sleep, for the given millisecond delay, but
478 >     * if the sleep is shorter than specified, may re-sleep or yield
479 >     * until time elapses.
480       */
481 <    public void threadUnexpectedException(Throwable ex) {
482 <        threadFailed = true;
483 <        ex.printStackTrace();
484 <        fail("Unexpected exception: " + ex);
481 >    static void delay(long millis) throws InterruptedException {
482 >        long startTime = System.nanoTime();
483 >        long ns = millis * 1000 * 1000;
484 >        for (;;) {
485 >            if (millis > 0L)
486 >                Thread.sleep(millis);
487 >            else // too short to sleep
488 >                Thread.yield();
489 >            long d = ns - (System.nanoTime() - startTime);
490 >            if (d > 0L)
491 >                millis = d / (1000 * 1000);
492 >            else
493 >                break;
494 >        }
495      }
496  
497      /**
498 <     * Wait out termination of a thread pool or fail doing so
498 >     * Waits out termination of a thread pool or fails doing so.
499       */
500 <    public void joinPool(ExecutorService exec) {
500 >    void joinPool(ExecutorService exec) {
501          try {
502              exec.shutdown();
503 <            assertTrue(exec.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
503 >            assertTrue("ExecutorService did not terminate in a timely manner",
504 >                       exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS));
505          } catch (SecurityException ok) {
506              // Allowed in case test doesn't have privs
507          } catch (InterruptedException ie) {
# Line 352 | Line 509 | public class JSR166TestCase extends Test
509          }
510      }
511  
512 +    /**
513 +     * Checks that thread does not terminate within the default
514 +     * millisecond delay of {@code timeoutMillis()}.
515 +     */
516 +    void assertThreadStaysAlive(Thread thread) {
517 +        assertThreadStaysAlive(thread, timeoutMillis());
518 +    }
519 +
520 +    /**
521 +     * Checks that thread does not terminate within the given millisecond delay.
522 +     */
523 +    void assertThreadStaysAlive(Thread thread, long millis) {
524 +        try {
525 +            // No need to optimize the failing case via Thread.join.
526 +            delay(millis);
527 +            assertTrue(thread.isAlive());
528 +        } catch (InterruptedException ie) {
529 +            fail("Unexpected InterruptedException");
530 +        }
531 +    }
532 +
533 +    /**
534 +     * Checks that the threads do not terminate within the default
535 +     * millisecond delay of {@code timeoutMillis()}.
536 +     */
537 +    void assertThreadsStayAlive(Thread... threads) {
538 +        assertThreadsStayAlive(timeoutMillis(), threads);
539 +    }
540  
541      /**
542 <     * fail with message "should throw exception"
542 >     * Checks that the threads do not terminate within the given millisecond delay.
543       */
544 <    public void shouldThrow() {
545 <        fail("Should throw exception");
544 >    void assertThreadsStayAlive(long millis, Thread... threads) {
545 >        try {
546 >            // No need to optimize the failing case via Thread.join.
547 >            delay(millis);
548 >            for (Thread thread : threads)
549 >                assertTrue(thread.isAlive());
550 >        } catch (InterruptedException ie) {
551 >            fail("Unexpected InterruptedException");
552 >        }
553      }
554  
555      /**
556 <     * fail with message "should throw " + exceptionName
556 >     * Checks that future.get times out, with the default timeout of
557 >     * {@code timeoutMillis()}.
558       */
559 <    public void shouldThrow(String exceptionName) {
560 <        fail("Should throw " + exceptionName);
559 >    void assertFutureTimesOut(Future future) {
560 >        assertFutureTimesOut(future, timeoutMillis());
561      }
562  
563      /**
564 <     * fail with message "Unexpected exception"
564 >     * Checks that future.get times out, with the given millisecond timeout.
565       */
566 <    public void unexpectedException() {
567 <        fail("Unexpected exception");
566 >    void assertFutureTimesOut(Future future, long timeoutMillis) {
567 >        long startTime = System.nanoTime();
568 >        try {
569 >            future.get(timeoutMillis, MILLISECONDS);
570 >            shouldThrow();
571 >        } catch (TimeoutException success) {
572 >        } catch (Exception e) {
573 >            threadUnexpectedException(e);
574 >        } finally { future.cancel(true); }
575 >        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
576      }
577  
578      /**
579 <     * fail with message "Unexpected exception", with argument
579 >     * Fails with message "should throw exception".
580       */
581 <    public void unexpectedException(Throwable ex) {
582 <        ex.printStackTrace();
382 <        fail("Unexpected exception: " + ex);
581 >    public void shouldThrow() {
582 >        fail("Should throw exception");
583      }
584  
585 +    /**
586 +     * Fails with message "should throw " + exceptionName.
587 +     */
588 +    public void shouldThrow(String exceptionName) {
589 +        fail("Should throw " + exceptionName);
590 +    }
591  
592      /**
593       * The number of elements to place in collections, arrays, etc.
# Line 420 | Line 626 | public class JSR166TestCase extends Test
626          SecurityManager sm = System.getSecurityManager();
627          if (sm == null) {
628              r.run();
629 +        }
630 +        runWithSecurityManagerWithPermissions(r, permissions);
631 +    }
632 +
633 +    /**
634 +     * Runs Runnable r with a security policy that permits precisely
635 +     * the specified permissions.  If there is no current security
636 +     * manager, a temporary one is set for the duration of the
637 +     * Runnable.  We require that any security manager permit
638 +     * getPolicy/setPolicy.
639 +     */
640 +    public void runWithSecurityManagerWithPermissions(Runnable r,
641 +                                                      Permission... permissions) {
642 +        SecurityManager sm = System.getSecurityManager();
643 +        if (sm == null) {
644              Policy savedPolicy = Policy.getPolicy();
645              try {
646                  Policy.setPolicy(permissivePolicy());
647                  System.setSecurityManager(new SecurityManager());
648 <                runWithPermissions(r, permissions);
648 >                runWithSecurityManagerWithPermissions(r, permissions);
649              } finally {
650                  System.setSecurityManager(null);
651                  Policy.setPolicy(savedPolicy);
# Line 472 | Line 693 | public class JSR166TestCase extends Test
693              return perms.implies(p);
694          }
695          public void refresh() {}
696 +        public String toString() {
697 +            List<Permission> ps = new ArrayList<Permission>();
698 +            for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
699 +                ps.add(e.nextElement());
700 +            return "AdjustablePolicy with permissions " + ps;
701 +        }
702      }
703  
704      /**
# Line 494 | Line 721 | public class JSR166TestCase extends Test
721      }
722  
723      /**
724 <     * Sleep until the timeout has elapsed, or interrupted.
725 <     * Does <em>NOT</em> throw InterruptedException.
724 >     * Sleeps until the given time has elapsed.
725 >     * Throws AssertionFailedError if interrupted.
726       */
727 <    void sleepTillInterrupted(long timeoutMillis) {
727 >    void sleep(long millis) {
728          try {
729 <            Thread.sleep(timeoutMillis);
730 <        } catch (InterruptedException wakeup) {}
729 >            delay(millis);
730 >        } catch (InterruptedException ie) {
731 >            AssertionFailedError afe =
732 >                new AssertionFailedError("Unexpected InterruptedException");
733 >            afe.initCause(ie);
734 >            throw afe;
735 >        }
736 >    }
737 >
738 >    /**
739 >     * Spin-waits up to the specified number of milliseconds for the given
740 >     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
741 >     */
742 >    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
743 >        long startTime = System.nanoTime();
744 >        for (;;) {
745 >            Thread.State s = thread.getState();
746 >            if (s == Thread.State.BLOCKED ||
747 >                s == Thread.State.WAITING ||
748 >                s == Thread.State.TIMED_WAITING)
749 >                return;
750 >            else if (s == Thread.State.TERMINATED)
751 >                fail("Unexpected thread termination");
752 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
753 >                threadAssertTrue(thread.isAlive());
754 >                return;
755 >            }
756 >            Thread.yield();
757 >        }
758      }
759  
760      /**
761 <     * Returns a new started Thread running the given runnable.
761 >     * Waits up to LONG_DELAY_MS for the given thread to enter a wait
762 >     * state: BLOCKED, WAITING, or TIMED_WAITING.
763 >     */
764 >    void waitForThreadToEnterWaitState(Thread thread) {
765 >        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
766 >    }
767 >
768 >    /**
769 >     * Returns the number of milliseconds since time given by
770 >     * startNanoTime, which must have been previously returned from a
771 >     * call to {@link System.nanoTime()}.
772 >     */
773 >    long millisElapsedSince(long startNanoTime) {
774 >        return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
775 >    }
776 >
777 >    /**
778 >     * Returns a new started daemon Thread running the given runnable.
779       */
780      Thread newStartedThread(Runnable runnable) {
781          Thread t = new Thread(runnable);
782 +        t.setDaemon(true);
783          t.start();
784          return t;
785      }
786  
787 +    /**
788 +     * Waits for the specified time (in milliseconds) for the thread
789 +     * to terminate (using {@link Thread#join(long)}), else interrupts
790 +     * the thread (in the hope that it may terminate later) and fails.
791 +     */
792 +    void awaitTermination(Thread t, long timeoutMillis) {
793 +        try {
794 +            t.join(timeoutMillis);
795 +        } catch (InterruptedException ie) {
796 +            threadUnexpectedException(ie);
797 +        } finally {
798 +            if (t.getState() != Thread.State.TERMINATED) {
799 +                t.interrupt();
800 +                fail("Test timed out");
801 +            }
802 +        }
803 +    }
804 +
805 +    /**
806 +     * Waits for LONG_DELAY_MS milliseconds for the thread to
807 +     * terminate (using {@link Thread#join(long)}), else interrupts
808 +     * the thread (in the hope that it may terminate later) and fails.
809 +     */
810 +    void awaitTermination(Thread t) {
811 +        awaitTermination(t, LONG_DELAY_MS);
812 +    }
813 +
814      // Some convenient Runnable classes
815  
816      public abstract class CheckedRunnable implements Runnable {
# Line 574 | Line 873 | public class JSR166TestCase extends Test
873                  realRun();
874                  threadShouldThrow("InterruptedException");
875              } catch (InterruptedException success) {
876 +                threadAssertFalse(Thread.interrupted());
877              } catch (Throwable t) {
878                  threadUnexpectedException(t);
879              }
# Line 588 | Line 888 | public class JSR166TestCase extends Test
888                  return realCall();
889              } catch (Throwable t) {
890                  threadUnexpectedException(t);
891 +                return null;
892              }
592            return null;
893          }
894      }
895  
896 <    public abstract class CheckedInterruptedCallable<T> implements Callable<T> {
896 >    public abstract class CheckedInterruptedCallable<T>
897 >        implements Callable<T> {
898          protected abstract T realCall() throws Throwable;
899  
900          public final T call() {
# Line 602 | Line 903 | public class JSR166TestCase extends Test
903                  threadShouldThrow("InterruptedException");
904                  return result;
905              } catch (InterruptedException success) {
906 +                threadAssertFalse(Thread.interrupted());
907              } catch (Throwable t) {
908                  threadUnexpectedException(t);
909              }
# Line 625 | Line 927 | public class JSR166TestCase extends Test
927  
928      public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
929          return new CheckedCallable<String>() {
930 <            public String realCall() {
930 >            protected String realCall() {
931                  try {
932                      latch.await();
933                  } catch (InterruptedException quittingTime) {}
# Line 633 | Line 935 | public class JSR166TestCase extends Test
935              }};
936      }
937  
938 +    public Runnable awaiter(final CountDownLatch latch) {
939 +        return new CheckedRunnable() {
940 +            public void realRun() throws InterruptedException {
941 +                await(latch);
942 +            }};
943 +    }
944 +
945 +    public void await(CountDownLatch latch) {
946 +        try {
947 +            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
948 +        } catch (Throwable t) {
949 +            threadUnexpectedException(t);
950 +        }
951 +    }
952 +
953 +    public void await(Semaphore semaphore) {
954 +        try {
955 +            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
956 +        } catch (Throwable t) {
957 +            threadUnexpectedException(t);
958 +        }
959 +    }
960 +
961 + //     /**
962 + //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
963 + //      */
964 + //     public void await(AtomicBoolean flag) {
965 + //         await(flag, LONG_DELAY_MS);
966 + //     }
967 +
968 + //     /**
969 + //      * Spin-waits up to the specified timeout until flag becomes true.
970 + //      */
971 + //     public void await(AtomicBoolean flag, long timeoutMillis) {
972 + //         long startTime = System.nanoTime();
973 + //         while (!flag.get()) {
974 + //             if (millisElapsedSince(startTime) > timeoutMillis)
975 + //                 throw new AssertionFailedError("timed out");
976 + //             Thread.yield();
977 + //         }
978 + //     }
979 +
980      public static class NPETask implements Callable<String> {
981          public String call() { throw new NullPointerException(); }
982      }
# Line 643 | Line 987 | public class JSR166TestCase extends Test
987  
988      public class ShortRunnable extends CheckedRunnable {
989          protected void realRun() throws Throwable {
990 <            Thread.sleep(SHORT_DELAY_MS);
990 >            delay(SHORT_DELAY_MS);
991          }
992      }
993  
994      public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
995          protected void realRun() throws InterruptedException {
996 <            Thread.sleep(SHORT_DELAY_MS);
996 >            delay(SHORT_DELAY_MS);
997          }
998      }
999  
1000      public class SmallRunnable extends CheckedRunnable {
1001          protected void realRun() throws Throwable {
1002 <            Thread.sleep(SMALL_DELAY_MS);
1002 >            delay(SMALL_DELAY_MS);
1003          }
1004      }
1005  
1006      public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1007          protected void realRun() {
1008              try {
1009 <                Thread.sleep(SMALL_DELAY_MS);
1009 >                delay(SMALL_DELAY_MS);
1010              } catch (InterruptedException ok) {}
1011          }
1012      }
1013  
1014      public class SmallCallable extends CheckedCallable {
1015          protected Object realCall() throws InterruptedException {
1016 <            Thread.sleep(SMALL_DELAY_MS);
1016 >            delay(SMALL_DELAY_MS);
1017              return Boolean.TRUE;
1018          }
1019      }
1020  
677    public class SmallInterruptedRunnable extends CheckedInterruptedRunnable {
678        protected void realRun() throws InterruptedException {
679            Thread.sleep(SMALL_DELAY_MS);
680        }
681    }
682
1021      public class MediumRunnable extends CheckedRunnable {
1022          protected void realRun() throws Throwable {
1023 <            Thread.sleep(MEDIUM_DELAY_MS);
1023 >            delay(MEDIUM_DELAY_MS);
1024          }
1025      }
1026  
1027      public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1028          protected void realRun() throws InterruptedException {
1029 <            Thread.sleep(MEDIUM_DELAY_MS);
1029 >            delay(MEDIUM_DELAY_MS);
1030          }
1031      }
1032  
1033 +    public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1034 +        return new CheckedRunnable() {
1035 +            protected void realRun() {
1036 +                try {
1037 +                    delay(timeoutMillis);
1038 +                } catch (InterruptedException ok) {}
1039 +            }};
1040 +    }
1041 +
1042      public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1043          protected void realRun() {
1044              try {
1045 <                Thread.sleep(MEDIUM_DELAY_MS);
1045 >                delay(MEDIUM_DELAY_MS);
1046              } catch (InterruptedException ok) {}
1047          }
1048      }
# Line 703 | Line 1050 | public class JSR166TestCase extends Test
1050      public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1051          protected void realRun() {
1052              try {
1053 <                Thread.sleep(LONG_DELAY_MS);
1053 >                delay(LONG_DELAY_MS);
1054              } catch (InterruptedException ok) {}
1055          }
1056      }
# Line 717 | Line 1064 | public class JSR166TestCase extends Test
1064          }
1065      }
1066  
1067 +    public interface TrackedRunnable extends Runnable {
1068 +        boolean isDone();
1069 +    }
1070 +
1071 +    public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
1072 +        return new TrackedRunnable() {
1073 +                private volatile boolean done = false;
1074 +                public boolean isDone() { return done; }
1075 +                public void run() {
1076 +                    try {
1077 +                        delay(timeoutMillis);
1078 +                        done = true;
1079 +                    } catch (InterruptedException ok) {}
1080 +                }
1081 +            };
1082 +    }
1083 +
1084      public static class TrackedShortRunnable implements Runnable {
1085          public volatile boolean done = false;
1086          public void run() {
1087              try {
1088 <                Thread.sleep(SMALL_DELAY_MS);
1088 >                delay(SHORT_DELAY_MS);
1089 >                done = true;
1090 >            } catch (InterruptedException ok) {}
1091 >        }
1092 >    }
1093 >
1094 >    public static class TrackedSmallRunnable implements Runnable {
1095 >        public volatile boolean done = false;
1096 >        public void run() {
1097 >            try {
1098 >                delay(SMALL_DELAY_MS);
1099                  done = true;
1100              } catch (InterruptedException ok) {}
1101          }
# Line 731 | Line 1105 | public class JSR166TestCase extends Test
1105          public volatile boolean done = false;
1106          public void run() {
1107              try {
1108 <                Thread.sleep(MEDIUM_DELAY_MS);
1108 >                delay(MEDIUM_DELAY_MS);
1109                  done = true;
1110              } catch (InterruptedException ok) {}
1111          }
# Line 741 | Line 1115 | public class JSR166TestCase extends Test
1115          public volatile boolean done = false;
1116          public void run() {
1117              try {
1118 <                Thread.sleep(LONG_DELAY_MS);
1118 >                delay(LONG_DELAY_MS);
1119                  done = true;
1120              } catch (InterruptedException ok) {}
1121          }
# Line 758 | Line 1132 | public class JSR166TestCase extends Test
1132          public volatile boolean done = false;
1133          public Object call() {
1134              try {
1135 <                Thread.sleep(SMALL_DELAY_MS);
1135 >                delay(SMALL_DELAY_MS);
1136                  done = true;
1137              } catch (InterruptedException ok) {}
1138              return Boolean.TRUE;
1139          }
1140      }
1141  
1142 +    /**
1143 +     * Analog of CheckedRunnable for RecursiveAction
1144 +     */
1145 +    public abstract class CheckedRecursiveAction extends RecursiveAction {
1146 +        protected abstract void realCompute() throws Throwable;
1147 +
1148 +        public final void compute() {
1149 +            try {
1150 +                realCompute();
1151 +            } catch (Throwable t) {
1152 +                threadUnexpectedException(t);
1153 +            }
1154 +        }
1155 +    }
1156 +
1157 +    /**
1158 +     * Analog of CheckedCallable for RecursiveTask
1159 +     */
1160 +    public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1161 +        protected abstract T realCompute() throws Throwable;
1162 +
1163 +        public final T compute() {
1164 +            try {
1165 +                return realCompute();
1166 +            } catch (Throwable t) {
1167 +                threadUnexpectedException(t);
1168 +                return null;
1169 +            }
1170 +        }
1171 +    }
1172  
1173      /**
1174       * For use as RejectedExecutionHandler in constructors
# Line 774 | Line 1178 | public class JSR166TestCase extends Test
1178                                        ThreadPoolExecutor executor) {}
1179      }
1180  
1181 +    /**
1182 +     * A CyclicBarrier that uses timed await and fails with
1183 +     * AssertionFailedErrors instead of throwing checked exceptions.
1184 +     */
1185 +    public class CheckedBarrier extends CyclicBarrier {
1186 +        public CheckedBarrier(int parties) { super(parties); }
1187 +
1188 +        public int await() {
1189 +            try {
1190 +                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1191 +            } catch (TimeoutException e) {
1192 +                throw new AssertionFailedError("timed out");
1193 +            } catch (Exception e) {
1194 +                AssertionFailedError afe =
1195 +                    new AssertionFailedError("Unexpected exception: " + e);
1196 +                afe.initCause(e);
1197 +                throw afe;
1198 +            }
1199 +        }
1200 +    }
1201 +
1202 +    void checkEmpty(BlockingQueue q) {
1203 +        try {
1204 +            assertTrue(q.isEmpty());
1205 +            assertEquals(0, q.size());
1206 +            assertNull(q.peek());
1207 +            assertNull(q.poll());
1208 +            assertNull(q.poll(0, MILLISECONDS));
1209 +            assertEquals(q.toString(), "[]");
1210 +            assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1211 +            assertFalse(q.iterator().hasNext());
1212 +            try {
1213 +                q.element();
1214 +                shouldThrow();
1215 +            } catch (NoSuchElementException success) {}
1216 +            try {
1217 +                q.iterator().next();
1218 +                shouldThrow();
1219 +            } catch (NoSuchElementException success) {}
1220 +            try {
1221 +                q.remove();
1222 +                shouldThrow();
1223 +            } catch (NoSuchElementException success) {}
1224 +        } catch (InterruptedException ie) {
1225 +            threadUnexpectedException(ie);
1226 +        }
1227 +    }
1228 +
1229 +    void assertSerialEquals(Object x, Object y) {
1230 +        assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1231 +    }
1232 +
1233 +    void assertNotSerialEquals(Object x, Object y) {
1234 +        assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1235 +    }
1236 +
1237 +    byte[] serialBytes(Object o) {
1238 +        try {
1239 +            ByteArrayOutputStream bos = new ByteArrayOutputStream();
1240 +            ObjectOutputStream oos = new ObjectOutputStream(bos);
1241 +            oos.writeObject(o);
1242 +            oos.flush();
1243 +            oos.close();
1244 +            return bos.toByteArray();
1245 +        } catch (Throwable t) {
1246 +            threadUnexpectedException(t);
1247 +            return new byte[0];
1248 +        }
1249 +    }
1250 +
1251 +    @SuppressWarnings("unchecked")
1252 +    <T> T serialClone(T o) {
1253 +        try {
1254 +            ObjectInputStream ois = new ObjectInputStream
1255 +                (new ByteArrayInputStream(serialBytes(o)));
1256 +            T clone = (T) ois.readObject();
1257 +            assertSame(o.getClass(), clone.getClass());
1258 +            return clone;
1259 +        } catch (Throwable t) {
1260 +            threadUnexpectedException(t);
1261 +            return null;
1262 +        }
1263 +    }
1264   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines