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.51 by jsr166, Wed Sep 1 06:41:55 2010 UTC vs.
Revision 1.95 by jsr166, Mon Jan 21 19:43:52 2013 UTC

# Line 1 | Line 1
1   /*
2   * Written by Doug Lea with assistance from members of JCP JSR-166
3   * Expert Group and released to the public domain, as explained at
4 < * http://creativecommons.org/licenses/publicdomain
4 > * http://creativecommons.org/publicdomain/zero/1.0/
5   * Other contributors include Andrew Wright, Jeffrey Hayes,
6   * Pat Fisher, Mike Judd.
7   */
8  
9   import junit.framework.*;
10 < import java.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
148 >     * Runs all JSR166 unit tests using junit.textui.TestRunner.
149 >     * Optional command line arg provides the number of iterations to
150 >     * repeat running the tests.
151       */
152      public static void main(String[] args) {
153          if (useSecurityManager) {
# Line 99 | Line 155 | public class JSR166TestCase extends Test
155              Policy.setPolicy(permissivePolicy());
156              System.setSecurityManager(new SecurityManager());
157          }
158 <        int iters = 1;
159 <        if (args.length > 0)
104 <            iters = Integer.parseInt(args[0]);
158 >        int iters = (args.length == 0) ? 1 : Integer.parseInt(args[0]);
159 >
160          Test s = suite();
161          for (int i = 0; i < iters; ++i) {
162              junit.textui.TestRunner.run(s);
# Line 111 | Line 166 | public class JSR166TestCase extends Test
166          System.exit(0);
167      }
168  
169 +    public static TestSuite newTestSuite(Object... suiteOrClasses) {
170 +        TestSuite suite = new TestSuite();
171 +        for (Object suiteOrClass : suiteOrClasses) {
172 +            if (suiteOrClass instanceof TestSuite)
173 +                suite.addTest((TestSuite) suiteOrClass);
174 +            else if (suiteOrClass instanceof Class)
175 +                suite.addTest(new TestSuite((Class<?>) suiteOrClass));
176 +            else
177 +                throw new ClassCastException("not a test suite or class");
178 +        }
179 +        return suite;
180 +    }
181 +
182      /**
183 <     * Collects all JSR166 unit tests as one suite
183 >     * Collects all JSR166 unit tests as one suite.
184       */
185      public static Test suite() {
186 <        TestSuite suite = new TestSuite("JSR166 Unit Tests");
187 <
188 <        suite.addTest(new TestSuite(ForkJoinPoolTest.class));
189 <        suite.addTest(new TestSuite(ForkJoinTaskTest.class));
190 <        suite.addTest(new TestSuite(RecursiveActionTest.class));
191 <        suite.addTest(new TestSuite(RecursiveTaskTest.class));
192 <        suite.addTest(new TestSuite(LinkedTransferQueueTest.class));
193 <        suite.addTest(new TestSuite(PhaserTest.class));
194 <        suite.addTest(new TestSuite(ThreadLocalRandomTest.class));
195 <        suite.addTest(new TestSuite(AbstractExecutorServiceTest.class));
196 <        suite.addTest(new TestSuite(AbstractQueueTest.class));
197 <        suite.addTest(new TestSuite(AbstractQueuedSynchronizerTest.class));
198 <        suite.addTest(new TestSuite(AbstractQueuedLongSynchronizerTest.class));
199 <        suite.addTest(new TestSuite(ArrayBlockingQueueTest.class));
200 <        suite.addTest(new TestSuite(ArrayDequeTest.class));
201 <        suite.addTest(new TestSuite(AtomicBooleanTest.class));
202 <        suite.addTest(new TestSuite(AtomicIntegerArrayTest.class));
203 <        suite.addTest(new TestSuite(AtomicIntegerFieldUpdaterTest.class));
204 <        suite.addTest(new TestSuite(AtomicIntegerTest.class));
205 <        suite.addTest(new TestSuite(AtomicLongArrayTest.class));
206 <        suite.addTest(new TestSuite(AtomicLongFieldUpdaterTest.class));
207 <        suite.addTest(new TestSuite(AtomicLongTest.class));
208 <        suite.addTest(new TestSuite(AtomicMarkableReferenceTest.class));
209 <        suite.addTest(new TestSuite(AtomicReferenceArrayTest.class));
210 <        suite.addTest(new TestSuite(AtomicReferenceFieldUpdaterTest.class));
211 <        suite.addTest(new TestSuite(AtomicReferenceTest.class));
212 <        suite.addTest(new TestSuite(AtomicStampedReferenceTest.class));
213 <        suite.addTest(new TestSuite(ConcurrentHashMapTest.class));
214 <        suite.addTest(new TestSuite(ConcurrentLinkedDequeTest.class));
215 <        suite.addTest(new TestSuite(ConcurrentLinkedQueueTest.class));
216 <        suite.addTest(new TestSuite(ConcurrentSkipListMapTest.class));
217 <        suite.addTest(new TestSuite(ConcurrentSkipListSubMapTest.class));
218 <        suite.addTest(new TestSuite(ConcurrentSkipListSetTest.class));
219 <        suite.addTest(new TestSuite(ConcurrentSkipListSubSetTest.class));
220 <        suite.addTest(new TestSuite(CopyOnWriteArrayListTest.class));
221 <        suite.addTest(new TestSuite(CopyOnWriteArraySetTest.class));
222 <        suite.addTest(new TestSuite(CountDownLatchTest.class));
223 <        suite.addTest(new TestSuite(CyclicBarrierTest.class));
224 <        suite.addTest(new TestSuite(DelayQueueTest.class));
225 <        suite.addTest(new TestSuite(EntryTest.class));
226 <        suite.addTest(new TestSuite(ExchangerTest.class));
227 <        suite.addTest(new TestSuite(ExecutorsTest.class));
228 <        suite.addTest(new TestSuite(ExecutorCompletionServiceTest.class));
229 <        suite.addTest(new TestSuite(FutureTaskTest.class));
230 <        suite.addTest(new TestSuite(LinkedBlockingDequeTest.class));
231 <        suite.addTest(new TestSuite(LinkedBlockingQueueTest.class));
232 <        suite.addTest(new TestSuite(LinkedListTest.class));
233 <        suite.addTest(new TestSuite(LockSupportTest.class));
234 <        suite.addTest(new TestSuite(PriorityBlockingQueueTest.class));
235 <        suite.addTest(new TestSuite(PriorityQueueTest.class));
236 <        suite.addTest(new TestSuite(ReentrantLockTest.class));
237 <        suite.addTest(new TestSuite(ReentrantReadWriteLockTest.class));
238 <        suite.addTest(new TestSuite(ScheduledExecutorTest.class));
239 <        suite.addTest(new TestSuite(ScheduledExecutorSubclassTest.class));
240 <        suite.addTest(new TestSuite(SemaphoreTest.class));
241 <        suite.addTest(new TestSuite(SynchronousQueueTest.class));
242 <        suite.addTest(new TestSuite(SystemTest.class));
243 <        suite.addTest(new TestSuite(ThreadLocalTest.class));
244 <        suite.addTest(new TestSuite(ThreadPoolExecutorTest.class));
245 <        suite.addTest(new TestSuite(ThreadPoolExecutorSubclassTest.class));
246 <        suite.addTest(new TestSuite(ThreadTest.class));
247 <        suite.addTest(new TestSuite(TimeUnitTest.class));
248 <        suite.addTest(new TestSuite(TreeMapTest.class));
249 <        suite.addTest(new TestSuite(TreeSetTest.class));
250 <        suite.addTest(new TestSuite(TreeSubMapTest.class));
183 <        suite.addTest(new TestSuite(TreeSubSetTest.class));
184 <
185 <        return suite;
186 >        return newTestSuite(
187 >            ForkJoinPoolTest.suite(),
188 >            ForkJoinTaskTest.suite(),
189 >            RecursiveActionTest.suite(),
190 >            RecursiveTaskTest.suite(),
191 >            LinkedTransferQueueTest.suite(),
192 >            PhaserTest.suite(),
193 >            ThreadLocalRandomTest.suite(),
194 >            AbstractExecutorServiceTest.suite(),
195 >            AbstractQueueTest.suite(),
196 >            AbstractQueuedSynchronizerTest.suite(),
197 >            AbstractQueuedLongSynchronizerTest.suite(),
198 >            ArrayBlockingQueueTest.suite(),
199 >            ArrayDequeTest.suite(),
200 >            AtomicBooleanTest.suite(),
201 >            AtomicIntegerArrayTest.suite(),
202 >            AtomicIntegerFieldUpdaterTest.suite(),
203 >            AtomicIntegerTest.suite(),
204 >            AtomicLongArrayTest.suite(),
205 >            AtomicLongFieldUpdaterTest.suite(),
206 >            AtomicLongTest.suite(),
207 >            AtomicMarkableReferenceTest.suite(),
208 >            AtomicReferenceArrayTest.suite(),
209 >            AtomicReferenceFieldUpdaterTest.suite(),
210 >            AtomicReferenceTest.suite(),
211 >            AtomicStampedReferenceTest.suite(),
212 >            ConcurrentHashMapTest.suite(),
213 >            ConcurrentLinkedDequeTest.suite(),
214 >            ConcurrentLinkedQueueTest.suite(),
215 >            ConcurrentSkipListMapTest.suite(),
216 >            ConcurrentSkipListSubMapTest.suite(),
217 >            ConcurrentSkipListSetTest.suite(),
218 >            ConcurrentSkipListSubSetTest.suite(),
219 >            CopyOnWriteArrayListTest.suite(),
220 >            CopyOnWriteArraySetTest.suite(),
221 >            CountDownLatchTest.suite(),
222 >            CyclicBarrierTest.suite(),
223 >            DelayQueueTest.suite(),
224 >            EntryTest.suite(),
225 >            ExchangerTest.suite(),
226 >            ExecutorsTest.suite(),
227 >            ExecutorCompletionServiceTest.suite(),
228 >            FutureTaskTest.suite(),
229 >            LinkedBlockingDequeTest.suite(),
230 >            LinkedBlockingQueueTest.suite(),
231 >            LinkedListTest.suite(),
232 >            LockSupportTest.suite(),
233 >            PriorityBlockingQueueTest.suite(),
234 >            PriorityQueueTest.suite(),
235 >            ReentrantLockTest.suite(),
236 >            ReentrantReadWriteLockTest.suite(),
237 >            ScheduledExecutorTest.suite(),
238 >            ScheduledExecutorSubclassTest.suite(),
239 >            SemaphoreTest.suite(),
240 >            SynchronousQueueTest.suite(),
241 >            SystemTest.suite(),
242 >            ThreadLocalTest.suite(),
243 >            ThreadPoolExecutorTest.suite(),
244 >            ThreadPoolExecutorSubclassTest.suite(),
245 >            ThreadTest.suite(),
246 >            TimeUnitTest.suite(),
247 >            TreeMapTest.suite(),
248 >            TreeSetTest.suite(),
249 >            TreeSubMapTest.suite(),
250 >            TreeSubSetTest.suite());
251      }
252  
253  
# Line 200 | Line 265 | public class JSR166TestCase extends Test
265          return 50;
266      }
267  
203
268      /**
269       * Sets delays as multiples of SHORT_DELAY.
270       */
271      protected void setDelays() {
272          SHORT_DELAY_MS = getShortDelay();
273 <        SMALL_DELAY_MS = SHORT_DELAY_MS * 5;
273 >        SMALL_DELAY_MS  = SHORT_DELAY_MS * 5;
274          MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
275 <        LONG_DELAY_MS = SHORT_DELAY_MS * 50;
275 >        LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
276      }
277  
278      /**
279 <     * Flag set true if any threadAssert methods fail
279 >     * Returns a timeout in milliseconds to be used in tests that
280 >     * verify that operations block or time out.
281       */
282 <    volatile boolean threadFailed;
282 >    long timeoutMillis() {
283 >        return SHORT_DELAY_MS / 4;
284 >    }
285  
286      /**
287 <     * Initializes test to indicate that no thread assertions have failed
287 >     * Returns a new Date instance representing a time delayMillis
288 >     * milliseconds in the future.
289       */
290 +    Date delayedDate(long delayMillis) {
291 +        return new Date(System.currentTimeMillis() + delayMillis);
292 +    }
293 +
294 +    /**
295 +     * The first exception encountered if any threadAssertXXX method fails.
296 +     */
297 +    private final AtomicReference<Throwable> threadFailure
298 +        = new AtomicReference<Throwable>(null);
299 +
300 +    /**
301 +     * Records an exception so that it can be rethrown later in the test
302 +     * harness thread, triggering a test case failure.  Only the first
303 +     * failure is recorded; subsequent calls to this method from within
304 +     * the same test have no effect.
305 +     */
306 +    public void threadRecordFailure(Throwable t) {
307 +        threadFailure.compareAndSet(null, t);
308 +    }
309 +
310      public void setUp() {
311          setDelays();
224        threadFailed = false;
312      }
313  
314      /**
315 <     * Triggers test case failure if any thread assertions have failed
316 <     */
317 <    public void tearDown() {
318 <        assertFalse(threadFailed);
315 >     * Extra checks that get done for all test cases.
316 >     *
317 >     * Triggers test case failure if any thread assertions have failed,
318 >     * by rethrowing, in the test harness thread, any exception recorded
319 >     * earlier by threadRecordFailure.
320 >     *
321 >     * Triggers test case failure if interrupt status is set in the main thread.
322 >     */
323 >    public void tearDown() throws Exception {
324 >        Throwable t = threadFailure.getAndSet(null);
325 >        if (t != null) {
326 >            if (t instanceof Error)
327 >                throw (Error) t;
328 >            else if (t instanceof RuntimeException)
329 >                throw (RuntimeException) t;
330 >            else if (t instanceof Exception)
331 >                throw (Exception) t;
332 >            else {
333 >                AssertionFailedError afe =
334 >                    new AssertionFailedError(t.toString());
335 >                afe.initCause(t);
336 >                throw afe;
337 >            }
338 >        }
339 >
340 >        if (Thread.interrupted())
341 >            throw new AssertionFailedError("interrupt status set in main thread");
342      }
343  
344      /**
345 <     * Fail, also setting status to indicate current testcase should fail
345 >     * Just like fail(reason), but additionally recording (using
346 >     * threadRecordFailure) any AssertionFailedError thrown, so that
347 >     * the current testcase will fail.
348       */
349      public void threadFail(String reason) {
350 <        threadFailed = true;
351 <        fail(reason);
350 >        try {
351 >            fail(reason);
352 >        } catch (AssertionFailedError t) {
353 >            threadRecordFailure(t);
354 >            fail(reason);
355 >        }
356      }
357  
358      /**
359 <     * If expression not true, set status to indicate current testcase
360 <     * should fail
359 >     * Just like assertTrue(b), but additionally recording (using
360 >     * threadRecordFailure) any AssertionFailedError thrown, so that
361 >     * the current testcase will fail.
362       */
363      public void threadAssertTrue(boolean b) {
364 <        if (!b) {
248 <            threadFailed = true;
364 >        try {
365              assertTrue(b);
366 +        } catch (AssertionFailedError t) {
367 +            threadRecordFailure(t);
368 +            throw t;
369          }
370      }
371  
372      /**
373 <     * If expression not false, set status to indicate current testcase
374 <     * should fail
373 >     * Just like assertFalse(b), but additionally recording (using
374 >     * threadRecordFailure) any AssertionFailedError thrown, so that
375 >     * the current testcase will fail.
376       */
377      public void threadAssertFalse(boolean b) {
378 <        if (b) {
259 <            threadFailed = true;
378 >        try {
379              assertFalse(b);
380 +        } catch (AssertionFailedError t) {
381 +            threadRecordFailure(t);
382 +            throw t;
383          }
384      }
385  
386      /**
387 <     * If argument not null, set status to indicate current testcase
388 <     * should fail
387 >     * Just like assertNull(x), but additionally recording (using
388 >     * threadRecordFailure) any AssertionFailedError thrown, so that
389 >     * the current testcase will fail.
390       */
391      public void threadAssertNull(Object x) {
392 <        if (x != null) {
270 <            threadFailed = true;
392 >        try {
393              assertNull(x);
394 +        } catch (AssertionFailedError t) {
395 +            threadRecordFailure(t);
396 +            throw t;
397          }
398      }
399  
400      /**
401 <     * If arguments not equal, set status to indicate current testcase
402 <     * should fail
401 >     * Just like assertEquals(x, y), but additionally recording (using
402 >     * threadRecordFailure) any AssertionFailedError thrown, so that
403 >     * the current testcase will fail.
404       */
405      public void threadAssertEquals(long x, long y) {
406 <        if (x != y) {
281 <            threadFailed = true;
406 >        try {
407              assertEquals(x, y);
408 +        } catch (AssertionFailedError t) {
409 +            threadRecordFailure(t);
410 +            throw t;
411          }
412      }
413  
414      /**
415 <     * If arguments not equal, set status to indicate current testcase
416 <     * should fail
415 >     * Just like assertEquals(x, y), but additionally recording (using
416 >     * threadRecordFailure) any AssertionFailedError thrown, so that
417 >     * the current testcase will fail.
418       */
419      public void threadAssertEquals(Object x, Object y) {
420 <        if (x != y && (x == null || !x.equals(y))) {
292 <            threadFailed = true;
420 >        try {
421              assertEquals(x, y);
422 +        } catch (AssertionFailedError t) {
423 +            threadRecordFailure(t);
424 +            throw t;
425 +        } catch (Throwable t) {
426 +            threadUnexpectedException(t);
427 +        }
428 +    }
429 +
430 +    /**
431 +     * Just like assertSame(x, y), but additionally recording (using
432 +     * threadRecordFailure) any AssertionFailedError thrown, so that
433 +     * the current testcase will fail.
434 +     */
435 +    public void threadAssertSame(Object x, Object y) {
436 +        try {
437 +            assertSame(x, y);
438 +        } catch (AssertionFailedError t) {
439 +            threadRecordFailure(t);
440 +            throw t;
441          }
442      }
443  
444      /**
445 <     * threadFail with message "should throw exception"
445 >     * Calls threadFail with message "should throw exception".
446       */
447      public void threadShouldThrow() {
448 <        threadFailed = true;
302 <        fail("should throw exception");
448 >        threadFail("should throw exception");
449      }
450  
451      /**
452 <     * threadFail with message "should throw" + exceptionName
452 >     * Calls threadFail with message "should throw" + exceptionName.
453       */
454      public void threadShouldThrow(String exceptionName) {
455 <        threadFailed = true;
310 <        fail("should throw " + exceptionName);
455 >        threadFail("should throw " + exceptionName);
456      }
457  
458      /**
459 <     * threadFail with message "Unexpected exception"
459 >     * Records the given exception using {@link #threadRecordFailure},
460 >     * then rethrows the exception, wrapping it in an
461 >     * AssertionFailedError if necessary.
462       */
463 <    public void threadUnexpectedException() {
464 <        threadFailed = true;
465 <        fail("Unexpected exception");
463 >    public void threadUnexpectedException(Throwable t) {
464 >        threadRecordFailure(t);
465 >        t.printStackTrace();
466 >        if (t instanceof RuntimeException)
467 >            throw (RuntimeException) t;
468 >        else if (t instanceof Error)
469 >            throw (Error) t;
470 >        else {
471 >            AssertionFailedError afe =
472 >                new AssertionFailedError("unexpected exception: " + t);
473 >            afe.initCause(t);
474 >            throw afe;
475 >        }
476      }
477  
478      /**
479 <     * threadFail with message "Unexpected exception", with argument
479 >     * Delays, via Thread.sleep, for the given millisecond delay, but
480 >     * if the sleep is shorter than specified, may re-sleep or yield
481 >     * until time elapses.
482       */
483 <    public void threadUnexpectedException(Throwable ex) {
484 <        threadFailed = true;
485 <        ex.printStackTrace();
486 <        fail("Unexpected exception: " + ex);
483 >    static void delay(long millis) throws InterruptedException {
484 >        long startTime = System.nanoTime();
485 >        long ns = millis * 1000 * 1000;
486 >        for (;;) {
487 >            if (millis > 0L)
488 >                Thread.sleep(millis);
489 >            else // too short to sleep
490 >                Thread.yield();
491 >            long d = ns - (System.nanoTime() - startTime);
492 >            if (d > 0L)
493 >                millis = d / (1000 * 1000);
494 >            else
495 >                break;
496 >        }
497      }
498  
499      /**
500 <     * Wait out termination of a thread pool or fail doing so
500 >     * Waits out termination of a thread pool or fails doing so.
501       */
502 <    public void joinPool(ExecutorService exec) {
502 >    void joinPool(ExecutorService exec) {
503          try {
504              exec.shutdown();
505 <            assertTrue(exec.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
505 >            assertTrue("ExecutorService did not terminate in a timely manner",
506 >                       exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS));
507          } catch (SecurityException ok) {
508              // Allowed in case test doesn't have privs
509          } catch (InterruptedException ie) {
# Line 341 | Line 511 | public class JSR166TestCase extends Test
511          }
512      }
513  
514 +    /**
515 +     * A debugging tool to print all stack traces, as jstack does.
516 +     */
517 +    void printAllStackTraces() {
518 +        System.err.println(
519 +            Arrays.toString(
520 +                java.lang.management.ManagementFactory.getThreadMXBean()
521 +                .dumpAllThreads(true, true)));
522 +    }
523  
524      /**
525 <     * fail with message "should throw exception"
525 >     * Checks that thread does not terminate within the default
526 >     * millisecond delay of {@code timeoutMillis()}.
527       */
528 <    public void shouldThrow() {
529 <        fail("Should throw exception");
528 >    void assertThreadStaysAlive(Thread thread) {
529 >        assertThreadStaysAlive(thread, timeoutMillis());
530      }
531  
532      /**
533 <     * fail with message "should throw " + exceptionName
533 >     * Checks that thread does not terminate within the given millisecond delay.
534       */
535 <    public void shouldThrow(String exceptionName) {
536 <        fail("Should throw " + exceptionName);
535 >    void assertThreadStaysAlive(Thread thread, long millis) {
536 >        try {
537 >            // No need to optimize the failing case via Thread.join.
538 >            delay(millis);
539 >            assertTrue(thread.isAlive());
540 >        } catch (InterruptedException ie) {
541 >            fail("Unexpected InterruptedException");
542 >        }
543 >    }
544 >
545 >    /**
546 >     * Checks that the threads do not terminate within the default
547 >     * millisecond delay of {@code timeoutMillis()}.
548 >     */
549 >    void assertThreadsStayAlive(Thread... threads) {
550 >        assertThreadsStayAlive(timeoutMillis(), threads);
551      }
552  
553      /**
554 <     * fail with message "Unexpected exception"
554 >     * Checks that the threads do not terminate within the given millisecond delay.
555       */
556 <    public void unexpectedException() {
557 <        fail("Unexpected exception");
556 >    void assertThreadsStayAlive(long millis, Thread... threads) {
557 >        try {
558 >            // No need to optimize the failing case via Thread.join.
559 >            delay(millis);
560 >            for (Thread thread : threads)
561 >                assertTrue(thread.isAlive());
562 >        } catch (InterruptedException ie) {
563 >            fail("Unexpected InterruptedException");
564 >        }
565      }
566  
567      /**
568 <     * fail with message "Unexpected exception", with argument
568 >     * Checks that future.get times out, with the default timeout of
569 >     * {@code timeoutMillis()}.
570       */
571 <    public void unexpectedException(Throwable ex) {
572 <        ex.printStackTrace();
371 <        fail("Unexpected exception: " + ex);
571 >    void assertFutureTimesOut(Future future) {
572 >        assertFutureTimesOut(future, timeoutMillis());
573      }
574  
575 +    /**
576 +     * Checks that future.get times out, with the given millisecond timeout.
577 +     */
578 +    void assertFutureTimesOut(Future future, long timeoutMillis) {
579 +        long startTime = System.nanoTime();
580 +        try {
581 +            future.get(timeoutMillis, MILLISECONDS);
582 +            shouldThrow();
583 +        } catch (TimeoutException success) {
584 +        } catch (Exception e) {
585 +            threadUnexpectedException(e);
586 +        } finally { future.cancel(true); }
587 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
588 +    }
589 +
590 +    /**
591 +     * Fails with message "should throw exception".
592 +     */
593 +    public void shouldThrow() {
594 +        fail("Should throw exception");
595 +    }
596 +
597 +    /**
598 +     * Fails with message "should throw " + exceptionName.
599 +     */
600 +    public void shouldThrow(String exceptionName) {
601 +        fail("Should throw " + exceptionName);
602 +    }
603  
604      /**
605       * The number of elements to place in collections, arrays, etc.
# Line 409 | Line 638 | public class JSR166TestCase extends Test
638          SecurityManager sm = System.getSecurityManager();
639          if (sm == null) {
640              r.run();
641 +        }
642 +        runWithSecurityManagerWithPermissions(r, permissions);
643 +    }
644 +
645 +    /**
646 +     * Runs Runnable r with a security policy that permits precisely
647 +     * the specified permissions.  If there is no current security
648 +     * manager, a temporary one is set for the duration of the
649 +     * Runnable.  We require that any security manager permit
650 +     * getPolicy/setPolicy.
651 +     */
652 +    public void runWithSecurityManagerWithPermissions(Runnable r,
653 +                                                      Permission... permissions) {
654 +        SecurityManager sm = System.getSecurityManager();
655 +        if (sm == null) {
656              Policy savedPolicy = Policy.getPolicy();
657              try {
658                  Policy.setPolicy(permissivePolicy());
659                  System.setSecurityManager(new SecurityManager());
660 <                runWithPermissions(r, permissions);
660 >                runWithSecurityManagerWithPermissions(r, permissions);
661              } finally {
662                  System.setSecurityManager(null);
663                  Policy.setPolicy(savedPolicy);
# Line 461 | Line 705 | public class JSR166TestCase extends Test
705              return perms.implies(p);
706          }
707          public void refresh() {}
708 +        public String toString() {
709 +            List<Permission> ps = new ArrayList<Permission>();
710 +            for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
711 +                ps.add(e.nextElement());
712 +            return "AdjustablePolicy with permissions " + ps;
713 +        }
714      }
715  
716      /**
# Line 483 | Line 733 | public class JSR166TestCase extends Test
733      }
734  
735      /**
736 <     * Sleep until the timeout has elapsed, or interrupted.
737 <     * Does <em>NOT</em> throw InterruptedException.
736 >     * Sleeps until the given time has elapsed.
737 >     * Throws AssertionFailedError if interrupted.
738       */
739 <    void sleepTillInterrupted(long timeoutMillis) {
739 >    void sleep(long millis) {
740          try {
741 <            Thread.sleep(timeoutMillis);
742 <        } catch (InterruptedException wakeup) {}
741 >            delay(millis);
742 >        } catch (InterruptedException ie) {
743 >            AssertionFailedError afe =
744 >                new AssertionFailedError("Unexpected InterruptedException");
745 >            afe.initCause(ie);
746 >            throw afe;
747 >        }
748 >    }
749 >
750 >    /**
751 >     * Spin-waits up to the specified number of milliseconds for the given
752 >     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
753 >     */
754 >    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
755 >        long startTime = System.nanoTime();
756 >        for (;;) {
757 >            Thread.State s = thread.getState();
758 >            if (s == Thread.State.BLOCKED ||
759 >                s == Thread.State.WAITING ||
760 >                s == Thread.State.TIMED_WAITING)
761 >                return;
762 >            else if (s == Thread.State.TERMINATED)
763 >                fail("Unexpected thread termination");
764 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
765 >                threadAssertTrue(thread.isAlive());
766 >                return;
767 >            }
768 >            Thread.yield();
769 >        }
770      }
771  
772      /**
773 <     * Returns a new started Thread running the given runnable.
773 >     * Waits up to LONG_DELAY_MS for the given thread to enter a wait
774 >     * state: BLOCKED, WAITING, or TIMED_WAITING.
775 >     */
776 >    void waitForThreadToEnterWaitState(Thread thread) {
777 >        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
778 >    }
779 >
780 >    /**
781 >     * Returns the number of milliseconds since time given by
782 >     * startNanoTime, which must have been previously returned from a
783 >     * call to {@link System.nanoTime()}.
784 >     */
785 >    long millisElapsedSince(long startNanoTime) {
786 >        return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
787 >    }
788 >
789 >    /**
790 >     * Returns a new started daemon Thread running the given runnable.
791       */
792      Thread newStartedThread(Runnable runnable) {
793          Thread t = new Thread(runnable);
794 +        t.setDaemon(true);
795          t.start();
796          return t;
797      }
798  
799 +    /**
800 +     * Waits for the specified time (in milliseconds) for the thread
801 +     * to terminate (using {@link Thread#join(long)}), else interrupts
802 +     * the thread (in the hope that it may terminate later) and fails.
803 +     */
804 +    void awaitTermination(Thread t, long timeoutMillis) {
805 +        try {
806 +            t.join(timeoutMillis);
807 +        } catch (InterruptedException ie) {
808 +            threadUnexpectedException(ie);
809 +        } finally {
810 +            if (t.getState() != Thread.State.TERMINATED) {
811 +                t.interrupt();
812 +                fail("Test timed out");
813 +            }
814 +        }
815 +    }
816 +
817 +    /**
818 +     * Waits for LONG_DELAY_MS milliseconds for the thread to
819 +     * terminate (using {@link Thread#join(long)}), else interrupts
820 +     * the thread (in the hope that it may terminate later) and fails.
821 +     */
822 +    void awaitTermination(Thread t) {
823 +        awaitTermination(t, LONG_DELAY_MS);
824 +    }
825 +
826      // Some convenient Runnable classes
827  
828      public abstract class CheckedRunnable implements Runnable {
# Line 563 | Line 885 | public class JSR166TestCase extends Test
885                  realRun();
886                  threadShouldThrow("InterruptedException");
887              } catch (InterruptedException success) {
888 +                threadAssertFalse(Thread.interrupted());
889              } catch (Throwable t) {
890                  threadUnexpectedException(t);
891              }
# Line 577 | Line 900 | public class JSR166TestCase extends Test
900                  return realCall();
901              } catch (Throwable t) {
902                  threadUnexpectedException(t);
903 +                return null;
904              }
581            return null;
905          }
906      }
907  
908 <    public abstract class CheckedInterruptedCallable<T> implements Callable<T> {
908 >    public abstract class CheckedInterruptedCallable<T>
909 >        implements Callable<T> {
910          protected abstract T realCall() throws Throwable;
911  
912          public final T call() {
# Line 591 | Line 915 | public class JSR166TestCase extends Test
915                  threadShouldThrow("InterruptedException");
916                  return result;
917              } catch (InterruptedException success) {
918 +                threadAssertFalse(Thread.interrupted());
919              } catch (Throwable t) {
920                  threadUnexpectedException(t);
921              }
# Line 614 | Line 939 | public class JSR166TestCase extends Test
939  
940      public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
941          return new CheckedCallable<String>() {
942 <            public String realCall() {
942 >            protected String realCall() {
943                  try {
944                      latch.await();
945                  } catch (InterruptedException quittingTime) {}
# Line 622 | Line 947 | public class JSR166TestCase extends Test
947              }};
948      }
949  
950 +    public Runnable awaiter(final CountDownLatch latch) {
951 +        return new CheckedRunnable() {
952 +            public void realRun() throws InterruptedException {
953 +                await(latch);
954 +            }};
955 +    }
956 +
957 +    public void await(CountDownLatch latch) {
958 +        try {
959 +            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
960 +        } catch (Throwable t) {
961 +            threadUnexpectedException(t);
962 +        }
963 +    }
964 +
965 +    public void await(Semaphore semaphore) {
966 +        try {
967 +            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
968 +        } catch (Throwable t) {
969 +            threadUnexpectedException(t);
970 +        }
971 +    }
972 +
973 + //     /**
974 + //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
975 + //      */
976 + //     public void await(AtomicBoolean flag) {
977 + //         await(flag, LONG_DELAY_MS);
978 + //     }
979 +
980 + //     /**
981 + //      * Spin-waits up to the specified timeout until flag becomes true.
982 + //      */
983 + //     public void await(AtomicBoolean flag, long timeoutMillis) {
984 + //         long startTime = System.nanoTime();
985 + //         while (!flag.get()) {
986 + //             if (millisElapsedSince(startTime) > timeoutMillis)
987 + //                 throw new AssertionFailedError("timed out");
988 + //             Thread.yield();
989 + //         }
990 + //     }
991 +
992      public static class NPETask implements Callable<String> {
993          public String call() { throw new NullPointerException(); }
994      }
# Line 632 | Line 999 | public class JSR166TestCase extends Test
999  
1000      public class ShortRunnable extends CheckedRunnable {
1001          protected void realRun() throws Throwable {
1002 <            Thread.sleep(SHORT_DELAY_MS);
1002 >            delay(SHORT_DELAY_MS);
1003          }
1004      }
1005  
1006      public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1007          protected void realRun() throws InterruptedException {
1008 <            Thread.sleep(SHORT_DELAY_MS);
1008 >            delay(SHORT_DELAY_MS);
1009          }
1010      }
1011  
1012      public class SmallRunnable extends CheckedRunnable {
1013          protected void realRun() throws Throwable {
1014 <            Thread.sleep(SMALL_DELAY_MS);
1014 >            delay(SMALL_DELAY_MS);
1015          }
1016      }
1017  
1018      public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1019          protected void realRun() {
1020              try {
1021 <                Thread.sleep(SMALL_DELAY_MS);
1021 >                delay(SMALL_DELAY_MS);
1022              } catch (InterruptedException ok) {}
1023          }
1024      }
1025  
1026      public class SmallCallable extends CheckedCallable {
1027          protected Object realCall() throws InterruptedException {
1028 <            Thread.sleep(SMALL_DELAY_MS);
1028 >            delay(SMALL_DELAY_MS);
1029              return Boolean.TRUE;
1030          }
1031      }
1032  
666    public class SmallInterruptedRunnable extends CheckedInterruptedRunnable {
667        protected void realRun() throws InterruptedException {
668            Thread.sleep(SMALL_DELAY_MS);
669        }
670    }
671
1033      public class MediumRunnable extends CheckedRunnable {
1034          protected void realRun() throws Throwable {
1035 <            Thread.sleep(MEDIUM_DELAY_MS);
1035 >            delay(MEDIUM_DELAY_MS);
1036          }
1037      }
1038  
1039      public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1040          protected void realRun() throws InterruptedException {
1041 <            Thread.sleep(MEDIUM_DELAY_MS);
1041 >            delay(MEDIUM_DELAY_MS);
1042          }
1043      }
1044  
1045 +    public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1046 +        return new CheckedRunnable() {
1047 +            protected void realRun() {
1048 +                try {
1049 +                    delay(timeoutMillis);
1050 +                } catch (InterruptedException ok) {}
1051 +            }};
1052 +    }
1053 +
1054      public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1055          protected void realRun() {
1056              try {
1057 <                Thread.sleep(MEDIUM_DELAY_MS);
1057 >                delay(MEDIUM_DELAY_MS);
1058              } catch (InterruptedException ok) {}
1059          }
1060      }
# Line 692 | Line 1062 | public class JSR166TestCase extends Test
1062      public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1063          protected void realRun() {
1064              try {
1065 <                Thread.sleep(LONG_DELAY_MS);
1065 >                delay(LONG_DELAY_MS);
1066              } catch (InterruptedException ok) {}
1067          }
1068      }
# Line 706 | Line 1076 | public class JSR166TestCase extends Test
1076          }
1077      }
1078  
1079 +    public interface TrackedRunnable extends Runnable {
1080 +        boolean isDone();
1081 +    }
1082 +
1083 +    public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
1084 +        return new TrackedRunnable() {
1085 +                private volatile boolean done = false;
1086 +                public boolean isDone() { return done; }
1087 +                public void run() {
1088 +                    try {
1089 +                        delay(timeoutMillis);
1090 +                        done = true;
1091 +                    } catch (InterruptedException ok) {}
1092 +                }
1093 +            };
1094 +    }
1095 +
1096      public static class TrackedShortRunnable implements Runnable {
1097          public volatile boolean done = false;
1098          public void run() {
1099              try {
1100 <                Thread.sleep(SMALL_DELAY_MS);
1100 >                delay(SHORT_DELAY_MS);
1101 >                done = true;
1102 >            } catch (InterruptedException ok) {}
1103 >        }
1104 >    }
1105 >
1106 >    public static class TrackedSmallRunnable implements Runnable {
1107 >        public volatile boolean done = false;
1108 >        public void run() {
1109 >            try {
1110 >                delay(SMALL_DELAY_MS);
1111                  done = true;
1112              } catch (InterruptedException ok) {}
1113          }
# Line 720 | Line 1117 | public class JSR166TestCase extends Test
1117          public volatile boolean done = false;
1118          public void run() {
1119              try {
1120 <                Thread.sleep(MEDIUM_DELAY_MS);
1120 >                delay(MEDIUM_DELAY_MS);
1121                  done = true;
1122              } catch (InterruptedException ok) {}
1123          }
# Line 730 | Line 1127 | public class JSR166TestCase extends Test
1127          public volatile boolean done = false;
1128          public void run() {
1129              try {
1130 <                Thread.sleep(LONG_DELAY_MS);
1130 >                delay(LONG_DELAY_MS);
1131                  done = true;
1132              } catch (InterruptedException ok) {}
1133          }
# Line 747 | Line 1144 | public class JSR166TestCase extends Test
1144          public volatile boolean done = false;
1145          public Object call() {
1146              try {
1147 <                Thread.sleep(SMALL_DELAY_MS);
1147 >                delay(SMALL_DELAY_MS);
1148                  done = true;
1149              } catch (InterruptedException ok) {}
1150              return Boolean.TRUE;
1151          }
1152      }
1153  
1154 +    /**
1155 +     * Analog of CheckedRunnable for RecursiveAction
1156 +     */
1157 +    public abstract class CheckedRecursiveAction extends RecursiveAction {
1158 +        protected abstract void realCompute() throws Throwable;
1159 +
1160 +        public final void compute() {
1161 +            try {
1162 +                realCompute();
1163 +            } catch (Throwable t) {
1164 +                threadUnexpectedException(t);
1165 +            }
1166 +        }
1167 +    }
1168 +
1169 +    /**
1170 +     * Analog of CheckedCallable for RecursiveTask
1171 +     */
1172 +    public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1173 +        protected abstract T realCompute() throws Throwable;
1174 +
1175 +        public final T compute() {
1176 +            try {
1177 +                return realCompute();
1178 +            } catch (Throwable t) {
1179 +                threadUnexpectedException(t);
1180 +                return null;
1181 +            }
1182 +        }
1183 +    }
1184  
1185      /**
1186       * For use as RejectedExecutionHandler in constructors
# Line 763 | Line 1190 | public class JSR166TestCase extends Test
1190                                        ThreadPoolExecutor executor) {}
1191      }
1192  
1193 +    /**
1194 +     * A CyclicBarrier that uses timed await and fails with
1195 +     * AssertionFailedErrors instead of throwing checked exceptions.
1196 +     */
1197 +    public class CheckedBarrier extends CyclicBarrier {
1198 +        public CheckedBarrier(int parties) { super(parties); }
1199 +
1200 +        public int await() {
1201 +            try {
1202 +                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1203 +            } catch (TimeoutException e) {
1204 +                throw new AssertionFailedError("timed out");
1205 +            } catch (Exception e) {
1206 +                AssertionFailedError afe =
1207 +                    new AssertionFailedError("Unexpected exception: " + e);
1208 +                afe.initCause(e);
1209 +                throw afe;
1210 +            }
1211 +        }
1212 +    }
1213 +
1214 +    void checkEmpty(BlockingQueue q) {
1215 +        try {
1216 +            assertTrue(q.isEmpty());
1217 +            assertEquals(0, q.size());
1218 +            assertNull(q.peek());
1219 +            assertNull(q.poll());
1220 +            assertNull(q.poll(0, MILLISECONDS));
1221 +            assertEquals(q.toString(), "[]");
1222 +            assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1223 +            assertFalse(q.iterator().hasNext());
1224 +            try {
1225 +                q.element();
1226 +                shouldThrow();
1227 +            } catch (NoSuchElementException success) {}
1228 +            try {
1229 +                q.iterator().next();
1230 +                shouldThrow();
1231 +            } catch (NoSuchElementException success) {}
1232 +            try {
1233 +                q.remove();
1234 +                shouldThrow();
1235 +            } catch (NoSuchElementException success) {}
1236 +        } catch (InterruptedException ie) {
1237 +            threadUnexpectedException(ie);
1238 +        }
1239 +    }
1240 +
1241 +    void assertSerialEquals(Object x, Object y) {
1242 +        assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1243 +    }
1244 +
1245 +    void assertNotSerialEquals(Object x, Object y) {
1246 +        assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1247 +    }
1248 +
1249 +    byte[] serialBytes(Object o) {
1250 +        try {
1251 +            ByteArrayOutputStream bos = new ByteArrayOutputStream();
1252 +            ObjectOutputStream oos = new ObjectOutputStream(bos);
1253 +            oos.writeObject(o);
1254 +            oos.flush();
1255 +            oos.close();
1256 +            return bos.toByteArray();
1257 +        } catch (Throwable t) {
1258 +            threadUnexpectedException(t);
1259 +            return new byte[0];
1260 +        }
1261 +    }
1262 +
1263 +    @SuppressWarnings("unchecked")
1264 +    <T> T serialClone(T o) {
1265 +        try {
1266 +            ObjectInputStream ois = new ObjectInputStream
1267 +                (new ByteArrayInputStream(serialBytes(o)));
1268 +            T clone = (T) ois.readObject();
1269 +            assertSame(o.getClass(), clone.getClass());
1270 +            return clone;
1271 +        } catch (Throwable t) {
1272 +            threadUnexpectedException(t);
1273 +            return null;
1274 +        }
1275 +    }
1276   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines