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.88 by jsr166, Tue May 31 15:01:24 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 238 | Line 307 | public class JSR166TestCase extends Test
307      }
308  
309      /**
310 +     * Extra checks that get done for all test cases.
311 +     *
312       * Triggers test case failure if any thread assertions have failed,
313       * by rethrowing, in the test harness thread, any exception recorded
314       * earlier by threadRecordFailure.
315 +     *
316 +     * Triggers test case failure if interrupt status is set in the main thread.
317       */
318      public void tearDown() throws Exception {
319 <        Throwable t = threadFailure.get();
319 >        Throwable t = threadFailure.getAndSet(null);
320          if (t != null) {
321              if (t instanceof Error)
322                  throw (Error) t;
# Line 251 | Line 324 | public class JSR166TestCase extends Test
324                  throw (RuntimeException) t;
325              else if (t instanceof Exception)
326                  throw (Exception) t;
327 <            else
328 <                throw new AssertionError(t);
327 >            else {
328 >                AssertionFailedError afe =
329 >                    new AssertionFailedError(t.toString());
330 >                afe.initCause(t);
331 >                throw afe;
332 >            }
333          }
334 +
335 +        if (Thread.interrupted())
336 +            throw new AssertionFailedError("interrupt status set in main thread");
337      }
338  
339      /**
340       * Just like fail(reason), but additionally recording (using
341 <     * threadRecordFailure) any AssertionError thrown, so that the current
342 <     * testcase will fail.
341 >     * threadRecordFailure) any AssertionFailedError thrown, so that
342 >     * the current testcase will fail.
343       */
344      public void threadFail(String reason) {
345          try {
346              fail(reason);
347 <        } catch (Throwable t) {
347 >        } catch (AssertionFailedError t) {
348              threadRecordFailure(t);
349              fail(reason);
350          }
# Line 272 | Line 352 | public class JSR166TestCase extends Test
352  
353      /**
354       * Just like assertTrue(b), but additionally recording (using
355 <     * threadRecordFailure) any AssertionError thrown, so that the current
356 <     * testcase will fail.
355 >     * threadRecordFailure) any AssertionFailedError thrown, so that
356 >     * the current testcase will fail.
357       */
358      public void threadAssertTrue(boolean b) {
359          try {
360              assertTrue(b);
361 <        } catch (AssertionError t) {
361 >        } catch (AssertionFailedError t) {
362              threadRecordFailure(t);
363              throw t;
364          }
# Line 286 | Line 366 | public class JSR166TestCase extends Test
366  
367      /**
368       * Just like assertFalse(b), but additionally recording (using
369 <     * threadRecordFailure) any AssertionError thrown, so that the
370 <     * current testcase will fail.
369 >     * threadRecordFailure) any AssertionFailedError thrown, so that
370 >     * the current testcase will fail.
371       */
372      public void threadAssertFalse(boolean b) {
373          try {
374              assertFalse(b);
375 <        } catch (AssertionError t) {
375 >        } catch (AssertionFailedError t) {
376              threadRecordFailure(t);
377              throw t;
378          }
# Line 300 | Line 380 | public class JSR166TestCase extends Test
380  
381      /**
382       * Just like assertNull(x), but additionally recording (using
383 <     * threadRecordFailure) any AssertionError thrown, so that the
384 <     * current testcase will fail.
383 >     * threadRecordFailure) any AssertionFailedError thrown, so that
384 >     * the current testcase will fail.
385       */
386      public void threadAssertNull(Object x) {
387          try {
388              assertNull(x);
389 <        } catch (AssertionError t) {
389 >        } catch (AssertionFailedError t) {
390              threadRecordFailure(t);
391              throw t;
392          }
# Line 314 | Line 394 | public class JSR166TestCase extends Test
394  
395      /**
396       * Just like assertEquals(x, y), but additionally recording (using
397 <     * threadRecordFailure) any AssertionError thrown, so that the
398 <     * current testcase will fail.
397 >     * threadRecordFailure) any AssertionFailedError thrown, so that
398 >     * the current testcase will fail.
399       */
400      public void threadAssertEquals(long x, long y) {
401          try {
402              assertEquals(x, y);
403 <        } catch (AssertionError t) {
403 >        } catch (AssertionFailedError t) {
404              threadRecordFailure(t);
405              throw t;
406          }
# Line 328 | Line 408 | public class JSR166TestCase extends Test
408  
409      /**
410       * Just like assertEquals(x, y), but additionally recording (using
411 <     * threadRecordFailure) any AssertionError thrown, so that the
412 <     * current testcase will fail.
411 >     * threadRecordFailure) any AssertionFailedError thrown, so that
412 >     * the current testcase will fail.
413       */
414      public void threadAssertEquals(Object x, Object y) {
415          try {
416              assertEquals(x, y);
417 <        } catch (AssertionError t) {
417 >        } catch (AssertionFailedError t) {
418              threadRecordFailure(t);
419              throw t;
420 +        } catch (Throwable t) {
421 +            threadUnexpectedException(t);
422          }
423      }
424  
425      /**
426       * Just like assertSame(x, y), but additionally recording (using
427 <     * threadRecordFailure) any AssertionError thrown, so that the
428 <     * current testcase will fail.
427 >     * threadRecordFailure) any AssertionFailedError thrown, so that
428 >     * the current testcase will fail.
429       */
430      public void threadAssertSame(Object x, Object y) {
431          try {
432              assertSame(x, y);
433 <        } catch (AssertionError t) {
433 >        } catch (AssertionFailedError t) {
434              threadRecordFailure(t);
435              throw t;
436          }
# Line 369 | Line 451 | public class JSR166TestCase extends Test
451      }
452  
453      /**
454 <     * Calls threadFail with message "Unexpected exception" + ex.
454 >     * Records the given exception using {@link #threadRecordFailure},
455 >     * then rethrows the exception, wrapping it in an
456 >     * AssertionFailedError if necessary.
457       */
458      public void threadUnexpectedException(Throwable t) {
459          threadRecordFailure(t);
460          t.printStackTrace();
377        // Rethrow, wrapping in an AssertionError if necessary
461          if (t instanceof RuntimeException)
462              throw (RuntimeException) t;
463          else if (t instanceof Error)
464              throw (Error) t;
465          else {
466 <            AssertionError ae = new AssertionError("unexpected exception: " + t);
467 <            t.initCause(t);
468 <            throw ae;
469 <        }            
466 >            AssertionFailedError afe =
467 >                new AssertionFailedError("unexpected exception: " + t);
468 >            afe.initCause(t);
469 >            throw afe;
470 >        }
471 >    }
472 >
473 >    /**
474 >     * Delays, via Thread.sleep, for the given millisecond delay, but
475 >     * if the sleep is shorter than specified, may re-sleep or yield
476 >     * until time elapses.
477 >     */
478 >    static void delay(long millis) throws InterruptedException {
479 >        long startTime = System.nanoTime();
480 >        long ns = millis * 1000 * 1000;
481 >        for (;;) {
482 >            if (millis > 0L)
483 >                Thread.sleep(millis);
484 >            else // too short to sleep
485 >                Thread.yield();
486 >            long d = ns - (System.nanoTime() - startTime);
487 >            if (d > 0L)
488 >                millis = d / (1000 * 1000);
489 >            else
490 >                break;
491 >        }
492      }
493  
494      /**
495       * Waits out termination of a thread pool or fails doing so.
496       */
497 <    public void joinPool(ExecutorService exec) {
497 >    void joinPool(ExecutorService exec) {
498          try {
499              exec.shutdown();
500              assertTrue("ExecutorService did not terminate in a timely manner",
501 <                       exec.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
501 >                       exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS));
502          } catch (SecurityException ok) {
503              // Allowed in case test doesn't have privs
504          } catch (InterruptedException ie) {
# Line 401 | Line 506 | public class JSR166TestCase extends Test
506          }
507      }
508  
509 +    /**
510 +     * Checks that thread does not terminate within the default
511 +     * millisecond delay of {@code timeoutMillis()}.
512 +     */
513 +    void assertThreadStaysAlive(Thread thread) {
514 +        assertThreadStaysAlive(thread, timeoutMillis());
515 +    }
516 +
517 +    /**
518 +     * Checks that thread does not terminate within the given millisecond delay.
519 +     */
520 +    void assertThreadStaysAlive(Thread thread, long millis) {
521 +        try {
522 +            // No need to optimize the failing case via Thread.join.
523 +            delay(millis);
524 +            assertTrue(thread.isAlive());
525 +        } catch (InterruptedException ie) {
526 +            fail("Unexpected InterruptedException");
527 +        }
528 +    }
529 +
530 +    /**
531 +     * Checks that future.get times out, with the default timeout of
532 +     * {@code timeoutMillis()}.
533 +     */
534 +    void assertFutureTimesOut(Future future) {
535 +        assertFutureTimesOut(future, timeoutMillis());
536 +    }
537 +
538 +    /**
539 +     * Checks that future.get times out, with the given millisecond timeout.
540 +     */
541 +    void assertFutureTimesOut(Future future, long timeoutMillis) {
542 +        long startTime = System.nanoTime();
543 +        try {
544 +            future.get(timeoutMillis, MILLISECONDS);
545 +            shouldThrow();
546 +        } catch (TimeoutException success) {
547 +        } catch (Exception e) {
548 +            threadUnexpectedException(e);
549 +        } finally { future.cancel(true); }
550 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
551 +    }
552  
553      /**
554       * Fails with message "should throw exception".
# Line 417 | Line 565 | public class JSR166TestCase extends Test
565      }
566  
567      /**
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    /**
568       * The number of elements to place in collections, arrays, etc.
569       */
570      public static final int SIZE = 20;
# Line 536 | Line 675 | public class JSR166TestCase extends Test
675      }
676  
677      /**
678 <     * Sleep until the timeout has elapsed, or interrupted.
679 <     * Does <em>NOT</em> throw InterruptedException.
678 >     * Sleeps until the given time has elapsed.
679 >     * Throws AssertionFailedError if interrupted.
680       */
681 <    void sleepTillInterrupted(long timeoutMillis) {
681 >    void sleep(long millis) {
682          try {
683 <            Thread.sleep(timeoutMillis);
684 <        } catch (InterruptedException wakeup) {}
683 >            delay(millis);
684 >        } catch (InterruptedException ie) {
685 >            AssertionFailedError afe =
686 >                new AssertionFailedError("Unexpected InterruptedException");
687 >            afe.initCause(ie);
688 >            throw afe;
689 >        }
690 >    }
691 >
692 >    /**
693 >     * Spin-waits up to the specified number of milliseconds for the given
694 >     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
695 >     */
696 >    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
697 >        long startTime = System.nanoTime();
698 >        for (;;) {
699 >            Thread.State s = thread.getState();
700 >            if (s == Thread.State.BLOCKED ||
701 >                s == Thread.State.WAITING ||
702 >                s == Thread.State.TIMED_WAITING)
703 >                return;
704 >            else if (s == Thread.State.TERMINATED)
705 >                fail("Unexpected thread termination");
706 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
707 >                threadAssertTrue(thread.isAlive());
708 >                return;
709 >            }
710 >            Thread.yield();
711 >        }
712 >    }
713 >
714 >    /**
715 >     * Waits up to LONG_DELAY_MS for the given thread to enter a wait
716 >     * state: BLOCKED, WAITING, or TIMED_WAITING.
717 >     */
718 >    void waitForThreadToEnterWaitState(Thread thread) {
719 >        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
720 >    }
721 >
722 >    /**
723 >     * Returns the number of milliseconds since time given by
724 >     * startNanoTime, which must have been previously returned from a
725 >     * call to {@link System.nanoTime()}.
726 >     */
727 >    long millisElapsedSince(long startNanoTime) {
728 >        return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
729      }
730  
731      /**
732 <     * Returns a new started Thread running the given runnable.
732 >     * Returns a new started daemon Thread running the given runnable.
733       */
734      Thread newStartedThread(Runnable runnable) {
735          Thread t = new Thread(runnable);
736 +        t.setDaemon(true);
737          t.start();
738          return t;
739      }
740  
741 +    /**
742 +     * Waits for the specified time (in milliseconds) for the thread
743 +     * to terminate (using {@link Thread#join(long)}), else interrupts
744 +     * the thread (in the hope that it may terminate later) and fails.
745 +     */
746 +    void awaitTermination(Thread t, long timeoutMillis) {
747 +        try {
748 +            t.join(timeoutMillis);
749 +        } catch (InterruptedException ie) {
750 +            threadUnexpectedException(ie);
751 +        } finally {
752 +            if (t.getState() != Thread.State.TERMINATED) {
753 +                t.interrupt();
754 +                fail("Test timed out");
755 +            }
756 +        }
757 +    }
758 +
759 +    /**
760 +     * Waits for LONG_DELAY_MS milliseconds for the thread to
761 +     * terminate (using {@link Thread#join(long)}), else interrupts
762 +     * the thread (in the hope that it may terminate later) and fails.
763 +     */
764 +    void awaitTermination(Thread t) {
765 +        awaitTermination(t, LONG_DELAY_MS);
766 +    }
767 +
768      // Some convenient Runnable classes
769  
770      public abstract class CheckedRunnable implements Runnable {
# Line 616 | Line 827 | public class JSR166TestCase extends Test
827                  realRun();
828                  threadShouldThrow("InterruptedException");
829              } catch (InterruptedException success) {
830 +                threadAssertFalse(Thread.interrupted());
831              } catch (Throwable t) {
832                  threadUnexpectedException(t);
833              }
# Line 645 | Line 857 | public class JSR166TestCase extends Test
857                  threadShouldThrow("InterruptedException");
858                  return result;
859              } catch (InterruptedException success) {
860 +                threadAssertFalse(Thread.interrupted());
861              } catch (Throwable t) {
862                  threadUnexpectedException(t);
863              }
# Line 668 | Line 881 | public class JSR166TestCase extends Test
881  
882      public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
883          return new CheckedCallable<String>() {
884 <            public String realCall() {
884 >            protected String realCall() {
885                  try {
886                      latch.await();
887                  } catch (InterruptedException quittingTime) {}
# Line 676 | Line 889 | public class JSR166TestCase extends Test
889              }};
890      }
891  
892 +    public Runnable awaiter(final CountDownLatch latch) {
893 +        return new CheckedRunnable() {
894 +            public void realRun() throws InterruptedException {
895 +                await(latch);
896 +            }};
897 +    }
898 +
899 +    public void await(CountDownLatch latch) {
900 +        try {
901 +            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
902 +        } catch (Throwable t) {
903 +            threadUnexpectedException(t);
904 +        }
905 +    }
906 +
907 + //     /**
908 + //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
909 + //      */
910 + //     public void await(AtomicBoolean flag) {
911 + //         await(flag, LONG_DELAY_MS);
912 + //     }
913 +
914 + //     /**
915 + //      * Spin-waits up to the specified timeout until flag becomes true.
916 + //      */
917 + //     public void await(AtomicBoolean flag, long timeoutMillis) {
918 + //         long startTime = System.nanoTime();
919 + //         while (!flag.get()) {
920 + //             if (millisElapsedSince(startTime) > timeoutMillis)
921 + //                 throw new AssertionFailedError("timed out");
922 + //             Thread.yield();
923 + //         }
924 + //     }
925 +
926      public static class NPETask implements Callable<String> {
927          public String call() { throw new NullPointerException(); }
928      }
# Line 686 | Line 933 | public class JSR166TestCase extends Test
933  
934      public class ShortRunnable extends CheckedRunnable {
935          protected void realRun() throws Throwable {
936 <            Thread.sleep(SHORT_DELAY_MS);
936 >            delay(SHORT_DELAY_MS);
937          }
938      }
939  
940      public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
941          protected void realRun() throws InterruptedException {
942 <            Thread.sleep(SHORT_DELAY_MS);
942 >            delay(SHORT_DELAY_MS);
943          }
944      }
945  
946      public class SmallRunnable extends CheckedRunnable {
947          protected void realRun() throws Throwable {
948 <            Thread.sleep(SMALL_DELAY_MS);
948 >            delay(SMALL_DELAY_MS);
949          }
950      }
951  
952      public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
953          protected void realRun() {
954              try {
955 <                Thread.sleep(SMALL_DELAY_MS);
955 >                delay(SMALL_DELAY_MS);
956              } catch (InterruptedException ok) {}
957          }
958      }
959  
960      public class SmallCallable extends CheckedCallable {
961          protected Object realCall() throws InterruptedException {
962 <            Thread.sleep(SMALL_DELAY_MS);
962 >            delay(SMALL_DELAY_MS);
963              return Boolean.TRUE;
964          }
965      }
966  
720    public class SmallInterruptedRunnable extends CheckedInterruptedRunnable {
721        protected void realRun() throws InterruptedException {
722            Thread.sleep(SMALL_DELAY_MS);
723        }
724    }
725
967      public class MediumRunnable extends CheckedRunnable {
968          protected void realRun() throws Throwable {
969 <            Thread.sleep(MEDIUM_DELAY_MS);
969 >            delay(MEDIUM_DELAY_MS);
970          }
971      }
972  
973      public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
974          protected void realRun() throws InterruptedException {
975 <            Thread.sleep(MEDIUM_DELAY_MS);
975 >            delay(MEDIUM_DELAY_MS);
976          }
977      }
978  
979 +    public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
980 +        return new CheckedRunnable() {
981 +            protected void realRun() {
982 +                try {
983 +                    delay(timeoutMillis);
984 +                } catch (InterruptedException ok) {}
985 +            }};
986 +    }
987 +
988      public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
989          protected void realRun() {
990              try {
991 <                Thread.sleep(MEDIUM_DELAY_MS);
991 >                delay(MEDIUM_DELAY_MS);
992              } catch (InterruptedException ok) {}
993          }
994      }
# Line 746 | Line 996 | public class JSR166TestCase extends Test
996      public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
997          protected void realRun() {
998              try {
999 <                Thread.sleep(LONG_DELAY_MS);
999 >                delay(LONG_DELAY_MS);
1000              } catch (InterruptedException ok) {}
1001          }
1002      }
# Line 760 | Line 1010 | public class JSR166TestCase extends Test
1010          }
1011      }
1012  
1013 +    public interface TrackedRunnable extends Runnable {
1014 +        boolean isDone();
1015 +    }
1016 +
1017 +    public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
1018 +        return new TrackedRunnable() {
1019 +                private volatile boolean done = false;
1020 +                public boolean isDone() { return done; }
1021 +                public void run() {
1022 +                    try {
1023 +                        delay(timeoutMillis);
1024 +                        done = true;
1025 +                    } catch (InterruptedException ok) {}
1026 +                }
1027 +            };
1028 +    }
1029 +
1030      public static class TrackedShortRunnable implements Runnable {
1031          public volatile boolean done = false;
1032          public void run() {
1033              try {
1034 <                Thread.sleep(SMALL_DELAY_MS);
1034 >                delay(SHORT_DELAY_MS);
1035 >                done = true;
1036 >            } catch (InterruptedException ok) {}
1037 >        }
1038 >    }
1039 >
1040 >    public static class TrackedSmallRunnable implements Runnable {
1041 >        public volatile boolean done = false;
1042 >        public void run() {
1043 >            try {
1044 >                delay(SMALL_DELAY_MS);
1045                  done = true;
1046              } catch (InterruptedException ok) {}
1047          }
# Line 774 | Line 1051 | public class JSR166TestCase extends Test
1051          public volatile boolean done = false;
1052          public void run() {
1053              try {
1054 <                Thread.sleep(MEDIUM_DELAY_MS);
1054 >                delay(MEDIUM_DELAY_MS);
1055                  done = true;
1056              } catch (InterruptedException ok) {}
1057          }
# Line 784 | Line 1061 | public class JSR166TestCase extends Test
1061          public volatile boolean done = false;
1062          public void run() {
1063              try {
1064 <                Thread.sleep(LONG_DELAY_MS);
1064 >                delay(LONG_DELAY_MS);
1065                  done = true;
1066              } catch (InterruptedException ok) {}
1067          }
# Line 801 | Line 1078 | public class JSR166TestCase extends Test
1078          public volatile boolean done = false;
1079          public Object call() {
1080              try {
1081 <                Thread.sleep(SMALL_DELAY_MS);
1081 >                delay(SMALL_DELAY_MS);
1082                  done = true;
1083              } catch (InterruptedException ok) {}
1084              return Boolean.TRUE;
# Line 847 | Line 1124 | public class JSR166TestCase extends Test
1124                                        ThreadPoolExecutor executor) {}
1125      }
1126  
1127 +    /**
1128 +     * A CyclicBarrier that uses timed await and fails with
1129 +     * AssertionFailedErrors instead of throwing checked exceptions.
1130 +     */
1131 +    public class CheckedBarrier extends CyclicBarrier {
1132 +        public CheckedBarrier(int parties) { super(parties); }
1133 +
1134 +        public int await() {
1135 +            try {
1136 +                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1137 +            } catch (TimeoutException e) {
1138 +                throw new AssertionFailedError("timed out");
1139 +            } catch (Exception e) {
1140 +                AssertionFailedError afe =
1141 +                    new AssertionFailedError("Unexpected exception: " + e);
1142 +                afe.initCause(e);
1143 +                throw afe;
1144 +            }
1145 +        }
1146 +    }
1147 +
1148 +    void checkEmpty(BlockingQueue q) {
1149 +        try {
1150 +            assertTrue(q.isEmpty());
1151 +            assertEquals(0, q.size());
1152 +            assertNull(q.peek());
1153 +            assertNull(q.poll());
1154 +            assertNull(q.poll(0, MILLISECONDS));
1155 +            assertEquals(q.toString(), "[]");
1156 +            assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1157 +            assertFalse(q.iterator().hasNext());
1158 +            try {
1159 +                q.element();
1160 +                shouldThrow();
1161 +            } catch (NoSuchElementException success) {}
1162 +            try {
1163 +                q.iterator().next();
1164 +                shouldThrow();
1165 +            } catch (NoSuchElementException success) {}
1166 +            try {
1167 +                q.remove();
1168 +                shouldThrow();
1169 +            } catch (NoSuchElementException success) {}
1170 +        } catch (InterruptedException ie) {
1171 +            threadUnexpectedException(ie);
1172 +        }
1173 +    }
1174 +
1175 +    @SuppressWarnings("unchecked")
1176 +    <T> T serialClone(T o) {
1177 +        try {
1178 +            ByteArrayOutputStream bos = new ByteArrayOutputStream();
1179 +            ObjectOutputStream oos = new ObjectOutputStream(bos);
1180 +            oos.writeObject(o);
1181 +            oos.flush();
1182 +            oos.close();
1183 +            ObjectInputStream ois = new ObjectInputStream
1184 +                (new ByteArrayInputStream(bos.toByteArray()));
1185 +            T clone = (T) ois.readObject();
1186 +            assertSame(o.getClass(), clone.getClass());
1187 +            return clone;
1188 +        } catch (Throwable t) {
1189 +            threadUnexpectedException(t);
1190 +            return null;
1191 +        }
1192 +    }
1193   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines