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.84 by jsr166, Sat May 28 22:19:27 2011 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.util.Arrays;
15 + import java.util.Date;
16 + import java.util.NoSuchElementException;
17   import java.util.PropertyPermission;
18   import java.util.concurrent.*;
19 + import java.util.concurrent.atomic.AtomicBoolean;
20   import java.util.concurrent.atomic.AtomicReference;
21   import static java.util.concurrent.TimeUnit.MILLISECONDS;
22 + import static java.util.concurrent.TimeUnit.NANOSECONDS;
23   import java.security.CodeSource;
24   import java.security.Permission;
25   import java.security.PermissionCollection;
# Line 96 | Line 105 | public class JSR166TestCase extends Test
105      private static final boolean useSecurityManager =
106          Boolean.getBoolean("jsr166.useSecurityManager");
107  
108 +    protected static final boolean expensiveTests =
109 +        Boolean.getBoolean("jsr166.expensiveTests");
110 +
111 +    /**
112 +     * If true, report on stdout all "slow" tests, that is, ones that
113 +     * take more than profileThreshold milliseconds to execute.
114 +     */
115 +    private static final boolean profileTests =
116 +        Boolean.getBoolean("jsr166.profileTests");
117 +
118 +    /**
119 +     * The number of milliseconds that tests are permitted for
120 +     * execution without being reported, when profileTests is set.
121 +     */
122 +    private static final long profileThreshold =
123 +        Long.getLong("jsr166.profileThreshold", 100);
124 +
125 +    protected void runTest() throws Throwable {
126 +        if (profileTests)
127 +            runTestProfiled();
128 +        else
129 +            super.runTest();
130 +    }
131 +
132 +    protected void runTestProfiled() throws Throwable {
133 +        long t0 = System.nanoTime();
134 +        try {
135 +            super.runTest();
136 +        } finally {
137 +            long elapsedMillis =
138 +                (System.nanoTime() - t0) / (1000L * 1000L);
139 +            if (elapsedMillis >= profileThreshold)
140 +                System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
141 +        }
142 +    }
143 +
144      /**
145       * Runs all JSR166 unit tests using junit.textui.TestRunner
146       */
# Line 105 | Line 150 | public class JSR166TestCase extends Test
150              Policy.setPolicy(permissivePolicy());
151              System.setSecurityManager(new SecurityManager());
152          }
153 <        int iters = 1;
154 <        if (args.length > 0)
110 <            iters = Integer.parseInt(args[0]);
153 >        int iters = (args.length == 0) ? 1 : Integer.parseInt(args[0]);
154 >
155          Test s = suite();
156          for (int i = 0; i < iters; ++i) {
157              junit.textui.TestRunner.run(s);
# Line 117 | Line 161 | public class JSR166TestCase extends Test
161          System.exit(0);
162      }
163  
164 +    public static TestSuite newTestSuite(Object... suiteOrClasses) {
165 +        TestSuite suite = new TestSuite();
166 +        for (Object suiteOrClass : suiteOrClasses) {
167 +            if (suiteOrClass instanceof TestSuite)
168 +                suite.addTest((TestSuite) suiteOrClass);
169 +            else if (suiteOrClass instanceof Class)
170 +                suite.addTest(new TestSuite((Class<?>) suiteOrClass));
171 +            else
172 +                throw new ClassCastException("not a test suite or class");
173 +        }
174 +        return suite;
175 +    }
176 +
177      /**
178 <     * Collects all JSR166 unit tests as one suite
178 >     * Collects all JSR166 unit tests as one suite.
179       */
180      public static Test suite() {
181 <        TestSuite suite = new TestSuite("JSR166 Unit Tests");
182 <
183 <        suite.addTest(new TestSuite(ForkJoinPoolTest.class));
184 <        suite.addTest(new TestSuite(ForkJoinTaskTest.class));
185 <        suite.addTest(new TestSuite(RecursiveActionTest.class));
186 <        suite.addTest(new TestSuite(RecursiveTaskTest.class));
187 <        suite.addTest(new TestSuite(LinkedTransferQueueTest.class));
188 <        suite.addTest(new TestSuite(PhaserTest.class));
189 <        suite.addTest(new TestSuite(ThreadLocalRandomTest.class));
190 <        suite.addTest(new TestSuite(AbstractExecutorServiceTest.class));
191 <        suite.addTest(new TestSuite(AbstractQueueTest.class));
192 <        suite.addTest(new TestSuite(AbstractQueuedSynchronizerTest.class));
193 <        suite.addTest(new TestSuite(AbstractQueuedLongSynchronizerTest.class));
194 <        suite.addTest(new TestSuite(ArrayBlockingQueueTest.class));
195 <        suite.addTest(new TestSuite(ArrayDequeTest.class));
196 <        suite.addTest(new TestSuite(AtomicBooleanTest.class));
197 <        suite.addTest(new TestSuite(AtomicIntegerArrayTest.class));
198 <        suite.addTest(new TestSuite(AtomicIntegerFieldUpdaterTest.class));
199 <        suite.addTest(new TestSuite(AtomicIntegerTest.class));
200 <        suite.addTest(new TestSuite(AtomicLongArrayTest.class));
201 <        suite.addTest(new TestSuite(AtomicLongFieldUpdaterTest.class));
202 <        suite.addTest(new TestSuite(AtomicLongTest.class));
203 <        suite.addTest(new TestSuite(AtomicMarkableReferenceTest.class));
204 <        suite.addTest(new TestSuite(AtomicReferenceArrayTest.class));
205 <        suite.addTest(new TestSuite(AtomicReferenceFieldUpdaterTest.class));
206 <        suite.addTest(new TestSuite(AtomicReferenceTest.class));
207 <        suite.addTest(new TestSuite(AtomicStampedReferenceTest.class));
208 <        suite.addTest(new TestSuite(ConcurrentHashMapTest.class));
209 <        suite.addTest(new TestSuite(ConcurrentLinkedDequeTest.class));
210 <        suite.addTest(new TestSuite(ConcurrentLinkedQueueTest.class));
211 <        suite.addTest(new TestSuite(ConcurrentSkipListMapTest.class));
212 <        suite.addTest(new TestSuite(ConcurrentSkipListSubMapTest.class));
213 <        suite.addTest(new TestSuite(ConcurrentSkipListSetTest.class));
214 <        suite.addTest(new TestSuite(ConcurrentSkipListSubSetTest.class));
215 <        suite.addTest(new TestSuite(CopyOnWriteArrayListTest.class));
216 <        suite.addTest(new TestSuite(CopyOnWriteArraySetTest.class));
217 <        suite.addTest(new TestSuite(CountDownLatchTest.class));
218 <        suite.addTest(new TestSuite(CyclicBarrierTest.class));
219 <        suite.addTest(new TestSuite(DelayQueueTest.class));
220 <        suite.addTest(new TestSuite(EntryTest.class));
221 <        suite.addTest(new TestSuite(ExchangerTest.class));
222 <        suite.addTest(new TestSuite(ExecutorsTest.class));
223 <        suite.addTest(new TestSuite(ExecutorCompletionServiceTest.class));
224 <        suite.addTest(new TestSuite(FutureTaskTest.class));
225 <        suite.addTest(new TestSuite(LinkedBlockingDequeTest.class));
226 <        suite.addTest(new TestSuite(LinkedBlockingQueueTest.class));
227 <        suite.addTest(new TestSuite(LinkedListTest.class));
228 <        suite.addTest(new TestSuite(LockSupportTest.class));
229 <        suite.addTest(new TestSuite(PriorityBlockingQueueTest.class));
230 <        suite.addTest(new TestSuite(PriorityQueueTest.class));
231 <        suite.addTest(new TestSuite(ReentrantLockTest.class));
232 <        suite.addTest(new TestSuite(ReentrantReadWriteLockTest.class));
233 <        suite.addTest(new TestSuite(ScheduledExecutorTest.class));
234 <        suite.addTest(new TestSuite(ScheduledExecutorSubclassTest.class));
235 <        suite.addTest(new TestSuite(SemaphoreTest.class));
236 <        suite.addTest(new TestSuite(SynchronousQueueTest.class));
237 <        suite.addTest(new TestSuite(SystemTest.class));
238 <        suite.addTest(new TestSuite(ThreadLocalTest.class));
239 <        suite.addTest(new TestSuite(ThreadPoolExecutorTest.class));
240 <        suite.addTest(new TestSuite(ThreadPoolExecutorSubclassTest.class));
241 <        suite.addTest(new TestSuite(ThreadTest.class));
242 <        suite.addTest(new TestSuite(TimeUnitTest.class));
243 <        suite.addTest(new TestSuite(TreeMapTest.class));
244 <        suite.addTest(new TestSuite(TreeSetTest.class));
245 <        suite.addTest(new TestSuite(TreeSubMapTest.class));
189 <        suite.addTest(new TestSuite(TreeSubSetTest.class));
190 <
191 <        return suite;
181 >        return newTestSuite(
182 >            ForkJoinPoolTest.suite(),
183 >            ForkJoinTaskTest.suite(),
184 >            RecursiveActionTest.suite(),
185 >            RecursiveTaskTest.suite(),
186 >            LinkedTransferQueueTest.suite(),
187 >            PhaserTest.suite(),
188 >            ThreadLocalRandomTest.suite(),
189 >            AbstractExecutorServiceTest.suite(),
190 >            AbstractQueueTest.suite(),
191 >            AbstractQueuedSynchronizerTest.suite(),
192 >            AbstractQueuedLongSynchronizerTest.suite(),
193 >            ArrayBlockingQueueTest.suite(),
194 >            ArrayDequeTest.suite(),
195 >            AtomicBooleanTest.suite(),
196 >            AtomicIntegerArrayTest.suite(),
197 >            AtomicIntegerFieldUpdaterTest.suite(),
198 >            AtomicIntegerTest.suite(),
199 >            AtomicLongArrayTest.suite(),
200 >            AtomicLongFieldUpdaterTest.suite(),
201 >            AtomicLongTest.suite(),
202 >            AtomicMarkableReferenceTest.suite(),
203 >            AtomicReferenceArrayTest.suite(),
204 >            AtomicReferenceFieldUpdaterTest.suite(),
205 >            AtomicReferenceTest.suite(),
206 >            AtomicStampedReferenceTest.suite(),
207 >            ConcurrentHashMapTest.suite(),
208 >            ConcurrentLinkedDequeTest.suite(),
209 >            ConcurrentLinkedQueueTest.suite(),
210 >            ConcurrentSkipListMapTest.suite(),
211 >            ConcurrentSkipListSubMapTest.suite(),
212 >            ConcurrentSkipListSetTest.suite(),
213 >            ConcurrentSkipListSubSetTest.suite(),
214 >            CopyOnWriteArrayListTest.suite(),
215 >            CopyOnWriteArraySetTest.suite(),
216 >            CountDownLatchTest.suite(),
217 >            CyclicBarrierTest.suite(),
218 >            DelayQueueTest.suite(),
219 >            EntryTest.suite(),
220 >            ExchangerTest.suite(),
221 >            ExecutorsTest.suite(),
222 >            ExecutorCompletionServiceTest.suite(),
223 >            FutureTaskTest.suite(),
224 >            LinkedBlockingDequeTest.suite(),
225 >            LinkedBlockingQueueTest.suite(),
226 >            LinkedListTest.suite(),
227 >            LockSupportTest.suite(),
228 >            PriorityBlockingQueueTest.suite(),
229 >            PriorityQueueTest.suite(),
230 >            ReentrantLockTest.suite(),
231 >            ReentrantReadWriteLockTest.suite(),
232 >            ScheduledExecutorTest.suite(),
233 >            ScheduledExecutorSubclassTest.suite(),
234 >            SemaphoreTest.suite(),
235 >            SynchronousQueueTest.suite(),
236 >            SystemTest.suite(),
237 >            ThreadLocalTest.suite(),
238 >            ThreadPoolExecutorTest.suite(),
239 >            ThreadPoolExecutorSubclassTest.suite(),
240 >            ThreadTest.suite(),
241 >            TimeUnitTest.suite(),
242 >            TreeMapTest.suite(),
243 >            TreeSetTest.suite(),
244 >            TreeSubMapTest.suite(),
245 >            TreeSubSetTest.suite());
246      }
247  
248  
# Line 206 | Line 260 | public class JSR166TestCase extends Test
260          return 50;
261      }
262  
209
263      /**
264       * Sets delays as multiples of SHORT_DELAY.
265       */
# Line 214 | Line 267 | public class JSR166TestCase extends Test
267          SHORT_DELAY_MS = getShortDelay();
268          SMALL_DELAY_MS  = SHORT_DELAY_MS * 5;
269          MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
270 <        LONG_DELAY_MS   = SHORT_DELAY_MS * 50;
270 >        LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
271 >    }
272 >
273 >    /**
274 >     * Returns a timeout in milliseconds to be used in tests that
275 >     * verify that operations block or time out.
276 >     */
277 >    long timeoutMillis() {
278 >        return SHORT_DELAY_MS / 4;
279 >    }
280 >
281 >    /**
282 >     * Returns a new Date instance representing a time delayMillis
283 >     * milliseconds in the future.
284 >     */
285 >    Date delayedDate(long delayMillis) {
286 >        return new Date(System.currentTimeMillis() + delayMillis);
287      }
288  
289      /**
# Line 243 | Line 312 | public class JSR166TestCase extends Test
312       * earlier by threadRecordFailure.
313       */
314      public void tearDown() throws Exception {
315 <        Throwable t = threadFailure.get();
315 >        Throwable t = threadFailure.getAndSet(null);
316          if (t != null) {
317              if (t instanceof Error)
318                  throw (Error) t;
# Line 251 | Line 320 | public class JSR166TestCase extends Test
320                  throw (RuntimeException) t;
321              else if (t instanceof Exception)
322                  throw (Exception) t;
323 <            else
324 <                throw new AssertionError(t);
323 >            else {
324 >                AssertionFailedError afe =
325 >                    new AssertionFailedError(t.toString());
326 >                afe.initCause(t);
327 >                throw afe;
328 >            }
329          }
330      }
331  
332      /**
333       * Just like fail(reason), but additionally recording (using
334 <     * threadRecordFailure) any AssertionError thrown, so that the current
335 <     * testcase will fail.
334 >     * threadRecordFailure) any AssertionFailedError thrown, so that
335 >     * the current testcase will fail.
336       */
337      public void threadFail(String reason) {
338          try {
339              fail(reason);
340 <        } catch (Throwable t) {
340 >        } catch (AssertionFailedError t) {
341              threadRecordFailure(t);
342              fail(reason);
343          }
# Line 272 | Line 345 | public class JSR166TestCase extends Test
345  
346      /**
347       * Just like assertTrue(b), but additionally recording (using
348 <     * threadRecordFailure) any AssertionError thrown, so that the current
349 <     * testcase will fail.
348 >     * threadRecordFailure) any AssertionFailedError thrown, so that
349 >     * the current testcase will fail.
350       */
351      public void threadAssertTrue(boolean b) {
352          try {
353              assertTrue(b);
354 <        } catch (AssertionError t) {
354 >        } catch (AssertionFailedError t) {
355              threadRecordFailure(t);
356              throw t;
357          }
# Line 286 | Line 359 | public class JSR166TestCase extends Test
359  
360      /**
361       * Just like assertFalse(b), but additionally recording (using
362 <     * threadRecordFailure) any AssertionError thrown, so that the
363 <     * current testcase will fail.
362 >     * threadRecordFailure) any AssertionFailedError thrown, so that
363 >     * the current testcase will fail.
364       */
365      public void threadAssertFalse(boolean b) {
366          try {
367              assertFalse(b);
368 <        } catch (AssertionError t) {
368 >        } catch (AssertionFailedError t) {
369              threadRecordFailure(t);
370              throw t;
371          }
# Line 300 | Line 373 | public class JSR166TestCase extends Test
373  
374      /**
375       * Just like assertNull(x), but additionally recording (using
376 <     * threadRecordFailure) any AssertionError thrown, so that the
377 <     * current testcase will fail.
376 >     * threadRecordFailure) any AssertionFailedError thrown, so that
377 >     * the current testcase will fail.
378       */
379      public void threadAssertNull(Object x) {
380          try {
381              assertNull(x);
382 <        } catch (AssertionError t) {
382 >        } catch (AssertionFailedError t) {
383              threadRecordFailure(t);
384              throw t;
385          }
# Line 314 | Line 387 | public class JSR166TestCase extends Test
387  
388      /**
389       * Just like assertEquals(x, y), but additionally recording (using
390 <     * threadRecordFailure) any AssertionError thrown, so that the
391 <     * current testcase will fail.
390 >     * threadRecordFailure) any AssertionFailedError thrown, so that
391 >     * the current testcase will fail.
392       */
393      public void threadAssertEquals(long x, long y) {
394          try {
395              assertEquals(x, y);
396 <        } catch (AssertionError t) {
396 >        } catch (AssertionFailedError t) {
397              threadRecordFailure(t);
398              throw t;
399          }
# Line 328 | Line 401 | public class JSR166TestCase extends Test
401  
402      /**
403       * Just like assertEquals(x, y), but additionally recording (using
404 <     * threadRecordFailure) any AssertionError thrown, so that the
405 <     * current testcase will fail.
404 >     * threadRecordFailure) any AssertionFailedError thrown, so that
405 >     * the current testcase will fail.
406       */
407      public void threadAssertEquals(Object x, Object y) {
408          try {
409              assertEquals(x, y);
410 <        } catch (AssertionError t) {
410 >        } catch (AssertionFailedError t) {
411              threadRecordFailure(t);
412              throw t;
413 +        } catch (Throwable t) {
414 +            threadUnexpectedException(t);
415          }
416      }
417  
418      /**
419       * Just like assertSame(x, y), but additionally recording (using
420 <     * threadRecordFailure) any AssertionError thrown, so that the
421 <     * current testcase will fail.
420 >     * threadRecordFailure) any AssertionFailedError thrown, so that
421 >     * the current testcase will fail.
422       */
423      public void threadAssertSame(Object x, Object y) {
424          try {
425              assertSame(x, y);
426 <        } catch (AssertionError t) {
426 >        } catch (AssertionFailedError t) {
427              threadRecordFailure(t);
428              throw t;
429          }
# Line 369 | Line 444 | public class JSR166TestCase extends Test
444      }
445  
446      /**
447 <     * Calls threadFail with message "Unexpected exception" + ex.
447 >     * Records the given exception using {@link #threadRecordFailure},
448 >     * then rethrows the exception, wrapping it in an
449 >     * AssertionFailedError if necessary.
450       */
451      public void threadUnexpectedException(Throwable t) {
452          threadRecordFailure(t);
453          t.printStackTrace();
377        // Rethrow, wrapping in an AssertionError if necessary
454          if (t instanceof RuntimeException)
455              throw (RuntimeException) t;
456          else if (t instanceof Error)
457              throw (Error) t;
458          else {
459 <            AssertionError ae = new AssertionError("unexpected exception: " + t);
460 <            t.initCause(t);
461 <            throw ae;
462 <        }            
459 >            AssertionFailedError afe =
460 >                new AssertionFailedError("unexpected exception: " + t);
461 >            afe.initCause(t);
462 >            throw afe;
463 >        }
464 >    }
465 >
466 >    /**
467 >     * Delays, via Thread.sleep, for the given millisecond delay, but
468 >     * if the sleep is shorter than specified, may re-sleep or yield
469 >     * until time elapses.
470 >     */
471 >    static void delay(long millis) throws InterruptedException {
472 >        long startTime = System.nanoTime();
473 >        long ns = millis * 1000 * 1000;
474 >        for (;;) {
475 >            if (millis > 0L)
476 >                Thread.sleep(millis);
477 >            else // too short to sleep
478 >                Thread.yield();
479 >            long d = ns - (System.nanoTime() - startTime);
480 >            if (d > 0L)
481 >                millis = d / (1000 * 1000);
482 >            else
483 >                break;
484 >        }
485      }
486  
487      /**
488       * Waits out termination of a thread pool or fails doing so.
489       */
490 <    public void joinPool(ExecutorService exec) {
490 >    void joinPool(ExecutorService exec) {
491          try {
492              exec.shutdown();
493              assertTrue("ExecutorService did not terminate in a timely manner",
494 <                       exec.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
494 >                       exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS));
495          } catch (SecurityException ok) {
496              // Allowed in case test doesn't have privs
497          } catch (InterruptedException ie) {
# Line 401 | Line 499 | public class JSR166TestCase extends Test
499          }
500      }
501  
502 +    /**
503 +     * Checks that thread does not terminate within the default
504 +     * millisecond delay of {@code timeoutMillis()}.
505 +     */
506 +    void assertThreadStaysAlive(Thread thread) {
507 +        assertThreadStaysAlive(thread, timeoutMillis());
508 +    }
509 +
510 +    /**
511 +     * Checks that thread does not terminate within the given millisecond delay.
512 +     */
513 +    void assertThreadStaysAlive(Thread thread, long millis) {
514 +        try {
515 +            // No need to optimize the failing case via Thread.join.
516 +            delay(millis);
517 +            assertTrue(thread.isAlive());
518 +        } catch (InterruptedException ie) {
519 +            fail("Unexpected InterruptedException");
520 +        }
521 +    }
522 +
523 +    /**
524 +     * Checks that future.get times out, with the default timeout of
525 +     * {@code timeoutMillis()}.
526 +     */
527 +    void assertFutureTimesOut(Future future) {
528 +        assertFutureTimesOut(future, timeoutMillis());
529 +    }
530 +
531 +    /**
532 +     * Checks that future.get times out, with the given millisecond timeout.
533 +     */
534 +    void assertFutureTimesOut(Future future, long timeoutMillis) {
535 +        long startTime = System.nanoTime();
536 +        try {
537 +            future.get(timeoutMillis, MILLISECONDS);
538 +            shouldThrow();
539 +        } catch (TimeoutException success) {
540 +        } catch (Exception e) {
541 +            threadUnexpectedException(e);
542 +        } finally { future.cancel(true); }
543 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
544 +    }
545  
546      /**
547       * Fails with message "should throw exception".
# Line 417 | Line 558 | public class JSR166TestCase extends Test
558      }
559  
560      /**
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    /**
561       * The number of elements to place in collections, arrays, etc.
562       */
563      public static final int SIZE = 20;
# Line 536 | Line 668 | public class JSR166TestCase extends Test
668      }
669  
670      /**
671 <     * Sleep until the timeout has elapsed, or interrupted.
672 <     * Does <em>NOT</em> throw InterruptedException.
671 >     * Sleeps until the given time has elapsed.
672 >     * Throws AssertionFailedError if interrupted.
673       */
674 <    void sleepTillInterrupted(long timeoutMillis) {
674 >    void sleep(long millis) {
675          try {
676 <            Thread.sleep(timeoutMillis);
677 <        } catch (InterruptedException wakeup) {}
676 >            delay(millis);
677 >        } catch (InterruptedException ie) {
678 >            AssertionFailedError afe =
679 >                new AssertionFailedError("Unexpected InterruptedException");
680 >            afe.initCause(ie);
681 >            throw afe;
682 >        }
683      }
684  
685      /**
686 <     * Returns a new started Thread running the given runnable.
686 >     * Waits up to the specified number of milliseconds for the given
687 >     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
688 >     */
689 >    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
690 >        long timeoutNanos = timeoutMillis * 1000L * 1000L;
691 >        long t0 = System.nanoTime();
692 >        for (;;) {
693 >            Thread.State s = thread.getState();
694 >            if (s == Thread.State.BLOCKED ||
695 >                s == Thread.State.WAITING ||
696 >                s == Thread.State.TIMED_WAITING)
697 >                return;
698 >            else if (s == Thread.State.TERMINATED)
699 >                fail("Unexpected thread termination");
700 >            else if (System.nanoTime() - t0 > timeoutNanos) {
701 >                threadAssertTrue(thread.isAlive());
702 >                return;
703 >            }
704 >            Thread.yield();
705 >        }
706 >    }
707 >
708 >    /**
709 >     * Waits up to LONG_DELAY_MS for the given thread to enter a wait
710 >     * state: BLOCKED, WAITING, or TIMED_WAITING.
711 >     */
712 >    void waitForThreadToEnterWaitState(Thread thread) {
713 >        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
714 >    }
715 >
716 >    /**
717 >     * Returns the number of milliseconds since time given by
718 >     * startNanoTime, which must have been previously returned from a
719 >     * call to {@link System.nanoTime()}.
720 >     */
721 >    long millisElapsedSince(long startNanoTime) {
722 >        return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
723 >    }
724 >
725 >    /**
726 >     * Returns a new started daemon Thread running the given runnable.
727       */
728      Thread newStartedThread(Runnable runnable) {
729          Thread t = new Thread(runnable);
730 +        t.setDaemon(true);
731          t.start();
732          return t;
733      }
734  
735 +    /**
736 +     * Waits for the specified time (in milliseconds) for the thread
737 +     * to terminate (using {@link Thread#join(long)}), else interrupts
738 +     * the thread (in the hope that it may terminate later) and fails.
739 +     */
740 +    void awaitTermination(Thread t, long timeoutMillis) {
741 +        try {
742 +            t.join(timeoutMillis);
743 +        } catch (InterruptedException ie) {
744 +            threadUnexpectedException(ie);
745 +        } finally {
746 +            if (t.getState() != Thread.State.TERMINATED) {
747 +                t.interrupt();
748 +                fail("Test timed out");
749 +            }
750 +        }
751 +    }
752 +
753 +    /**
754 +     * Waits for LONG_DELAY_MS milliseconds for the thread to
755 +     * terminate (using {@link Thread#join(long)}), else interrupts
756 +     * the thread (in the hope that it may terminate later) and fails.
757 +     */
758 +    void awaitTermination(Thread t) {
759 +        awaitTermination(t, LONG_DELAY_MS);
760 +    }
761 +
762      // Some convenient Runnable classes
763  
764      public abstract class CheckedRunnable implements Runnable {
# Line 616 | Line 821 | public class JSR166TestCase extends Test
821                  realRun();
822                  threadShouldThrow("InterruptedException");
823              } catch (InterruptedException success) {
824 +                threadAssertFalse(Thread.interrupted());
825              } catch (Throwable t) {
826                  threadUnexpectedException(t);
827              }
# Line 645 | Line 851 | public class JSR166TestCase extends Test
851                  threadShouldThrow("InterruptedException");
852                  return result;
853              } catch (InterruptedException success) {
854 +                threadAssertFalse(Thread.interrupted());
855              } catch (Throwable t) {
856                  threadUnexpectedException(t);
857              }
# Line 668 | Line 875 | public class JSR166TestCase extends Test
875  
876      public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
877          return new CheckedCallable<String>() {
878 <            public String realCall() {
878 >            protected String realCall() {
879                  try {
880                      latch.await();
881                  } catch (InterruptedException quittingTime) {}
# Line 676 | Line 883 | public class JSR166TestCase extends Test
883              }};
884      }
885  
886 +    public Runnable awaiter(final CountDownLatch latch) {
887 +        return new CheckedRunnable() {
888 +            public void realRun() throws InterruptedException {
889 +                await(latch);
890 +            }};
891 +    }
892 +
893 +    public void await(CountDownLatch latch) {
894 +        try {
895 +            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
896 +        } catch (Throwable t) {
897 +            threadUnexpectedException(t);
898 +        }
899 +    }
900 +
901 + //     /**
902 + //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
903 + //      */
904 + //     public void await(AtomicBoolean flag) {
905 + //         await(flag, LONG_DELAY_MS);
906 + //     }
907 +
908 + //     /**
909 + //      * Spin-waits up to the specified timeout until flag becomes true.
910 + //      */
911 + //     public void await(AtomicBoolean flag, long timeoutMillis) {
912 + //         long startTime = System.nanoTime();
913 + //         while (!flag.get()) {
914 + //             if (millisElapsedSince(startTime) > timeoutMillis)
915 + //                 throw new AssertionFailedError("timed out");
916 + //             Thread.yield();
917 + //         }
918 + //     }
919 +
920      public static class NPETask implements Callable<String> {
921          public String call() { throw new NullPointerException(); }
922      }
# Line 686 | Line 927 | public class JSR166TestCase extends Test
927  
928      public class ShortRunnable extends CheckedRunnable {
929          protected void realRun() throws Throwable {
930 <            Thread.sleep(SHORT_DELAY_MS);
930 >            delay(SHORT_DELAY_MS);
931          }
932      }
933  
934      public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
935          protected void realRun() throws InterruptedException {
936 <            Thread.sleep(SHORT_DELAY_MS);
936 >            delay(SHORT_DELAY_MS);
937          }
938      }
939  
940      public class SmallRunnable extends CheckedRunnable {
941          protected void realRun() throws Throwable {
942 <            Thread.sleep(SMALL_DELAY_MS);
942 >            delay(SMALL_DELAY_MS);
943          }
944      }
945  
946      public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
947          protected void realRun() {
948              try {
949 <                Thread.sleep(SMALL_DELAY_MS);
949 >                delay(SMALL_DELAY_MS);
950              } catch (InterruptedException ok) {}
951          }
952      }
953  
954      public class SmallCallable extends CheckedCallable {
955          protected Object realCall() throws InterruptedException {
956 <            Thread.sleep(SMALL_DELAY_MS);
956 >            delay(SMALL_DELAY_MS);
957              return Boolean.TRUE;
958          }
959      }
960  
720    public class SmallInterruptedRunnable extends CheckedInterruptedRunnable {
721        protected void realRun() throws InterruptedException {
722            Thread.sleep(SMALL_DELAY_MS);
723        }
724    }
725
961      public class MediumRunnable extends CheckedRunnable {
962          protected void realRun() throws Throwable {
963 <            Thread.sleep(MEDIUM_DELAY_MS);
963 >            delay(MEDIUM_DELAY_MS);
964          }
965      }
966  
967      public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
968          protected void realRun() throws InterruptedException {
969 <            Thread.sleep(MEDIUM_DELAY_MS);
969 >            delay(MEDIUM_DELAY_MS);
970          }
971      }
972  
973 +    public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
974 +        return new CheckedRunnable() {
975 +            protected void realRun() {
976 +                try {
977 +                    delay(timeoutMillis);
978 +                } catch (InterruptedException ok) {}
979 +            }};
980 +    }
981 +
982      public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
983          protected void realRun() {
984              try {
985 <                Thread.sleep(MEDIUM_DELAY_MS);
985 >                delay(MEDIUM_DELAY_MS);
986              } catch (InterruptedException ok) {}
987          }
988      }
# Line 746 | Line 990 | public class JSR166TestCase extends Test
990      public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
991          protected void realRun() {
992              try {
993 <                Thread.sleep(LONG_DELAY_MS);
993 >                delay(LONG_DELAY_MS);
994              } catch (InterruptedException ok) {}
995          }
996      }
# Line 760 | Line 1004 | public class JSR166TestCase extends Test
1004          }
1005      }
1006  
1007 +    public interface TrackedRunnable extends Runnable {
1008 +        boolean isDone();
1009 +    }
1010 +
1011 +    public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
1012 +        return new TrackedRunnable() {
1013 +                private volatile boolean done = false;
1014 +                public boolean isDone() { return done; }
1015 +                public void run() {
1016 +                    try {
1017 +                        delay(timeoutMillis);
1018 +                        done = true;
1019 +                    } catch (InterruptedException ok) {}
1020 +                }
1021 +            };
1022 +    }
1023 +
1024      public static class TrackedShortRunnable implements Runnable {
1025          public volatile boolean done = false;
1026          public void run() {
1027              try {
1028 <                Thread.sleep(SMALL_DELAY_MS);
1028 >                delay(SHORT_DELAY_MS);
1029 >                done = true;
1030 >            } catch (InterruptedException ok) {}
1031 >        }
1032 >    }
1033 >
1034 >    public static class TrackedSmallRunnable implements Runnable {
1035 >        public volatile boolean done = false;
1036 >        public void run() {
1037 >            try {
1038 >                delay(SMALL_DELAY_MS);
1039                  done = true;
1040              } catch (InterruptedException ok) {}
1041          }
# Line 774 | Line 1045 | public class JSR166TestCase extends Test
1045          public volatile boolean done = false;
1046          public void run() {
1047              try {
1048 <                Thread.sleep(MEDIUM_DELAY_MS);
1048 >                delay(MEDIUM_DELAY_MS);
1049                  done = true;
1050              } catch (InterruptedException ok) {}
1051          }
# Line 784 | Line 1055 | public class JSR166TestCase extends Test
1055          public volatile boolean done = false;
1056          public void run() {
1057              try {
1058 <                Thread.sleep(LONG_DELAY_MS);
1058 >                delay(LONG_DELAY_MS);
1059                  done = true;
1060              } catch (InterruptedException ok) {}
1061          }
# Line 801 | Line 1072 | public class JSR166TestCase extends Test
1072          public volatile boolean done = false;
1073          public Object call() {
1074              try {
1075 <                Thread.sleep(SMALL_DELAY_MS);
1075 >                delay(SMALL_DELAY_MS);
1076                  done = true;
1077              } catch (InterruptedException ok) {}
1078              return Boolean.TRUE;
# Line 847 | Line 1118 | public class JSR166TestCase extends Test
1118                                        ThreadPoolExecutor executor) {}
1119      }
1120  
1121 +    /**
1122 +     * A CyclicBarrier that fails with AssertionFailedErrors instead
1123 +     * of throwing checked exceptions.
1124 +     */
1125 +    public class CheckedBarrier extends CyclicBarrier {
1126 +        public CheckedBarrier(int parties) { super(parties); }
1127 +
1128 +        public int await() {
1129 +            try {
1130 +                return super.await();
1131 +            } catch (Exception e) {
1132 +                AssertionFailedError afe =
1133 +                    new AssertionFailedError("Unexpected exception: " + e);
1134 +                afe.initCause(e);
1135 +                throw afe;
1136 +            }
1137 +        }
1138 +    }
1139 +
1140 +    void checkEmpty(BlockingQueue q) {
1141 +        try {
1142 +            assertTrue(q.isEmpty());
1143 +            assertEquals(0, q.size());
1144 +            assertNull(q.peek());
1145 +            assertNull(q.poll());
1146 +            assertNull(q.poll(0, MILLISECONDS));
1147 +            assertEquals(q.toString(), "[]");
1148 +            assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1149 +            assertFalse(q.iterator().hasNext());
1150 +            try {
1151 +                q.element();
1152 +                shouldThrow();
1153 +            } catch (NoSuchElementException success) {}
1154 +            try {
1155 +                q.iterator().next();
1156 +                shouldThrow();
1157 +            } catch (NoSuchElementException success) {}
1158 +            try {
1159 +                q.remove();
1160 +                shouldThrow();
1161 +            } catch (NoSuchElementException success) {}
1162 +        } catch (InterruptedException ie) {
1163 +            threadUnexpectedException(ie);
1164 +        }
1165 +    }
1166 +
1167 +    @SuppressWarnings("unchecked")
1168 +    <T> T serialClone(T o) {
1169 +        try {
1170 +            ByteArrayOutputStream bos = new ByteArrayOutputStream();
1171 +            ObjectOutputStream oos = new ObjectOutputStream(bos);
1172 +            oos.writeObject(o);
1173 +            oos.flush();
1174 +            oos.close();
1175 +            ByteArrayInputStream bin =
1176 +                new ByteArrayInputStream(bos.toByteArray());
1177 +            ObjectInputStream ois = new ObjectInputStream(bin);
1178 +            return (T) ois.readObject();
1179 +        } catch (Throwable t) {
1180 +            threadUnexpectedException(t);
1181 +            return null;
1182 +        }
1183 +    }
1184   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines