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.97 by jsr166, Fri Feb 1 19:07:36 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.lang.management.ManagementFactory;
15 > import java.lang.management.ThreadInfo;
16 > import java.lang.reflect.Method;
17 > import java.util.ArrayList;
18 > import java.util.Arrays;
19 > import java.util.Date;
20 > import java.util.Enumeration;
21 > import java.util.List;
22 > import java.util.NoSuchElementException;
23 > import java.util.PropertyPermission;
24   import java.util.concurrent.*;
25 + import java.util.concurrent.atomic.AtomicBoolean;
26 + import java.util.concurrent.atomic.AtomicReference;
27   import static java.util.concurrent.TimeUnit.MILLISECONDS;
28 < import java.io.*;
29 < import java.security.*;
28 > import static java.util.concurrent.TimeUnit.NANOSECONDS;
29 > import java.security.CodeSource;
30 > import java.security.Permission;
31 > import java.security.PermissionCollection;
32 > import java.security.Permissions;
33 > import java.security.Policy;
34 > import java.security.ProtectionDomain;
35 > import java.security.SecurityPermission;
36  
37   /**
38   * Base class for JSR166 Junit TCK tests.  Defines some constants,
# Line 54 | Line 75 | import java.security.*;
75   *
76   * </ol>
77   *
78 < * <p> <b>Other notes</b>
78 > * <p><b>Other notes</b>
79   * <ul>
80   *
81   * <li> Usually, there is one testcase method per JSR166 method
# Line 90 | Line 111 | public class JSR166TestCase extends Test
111      private static final boolean useSecurityManager =
112          Boolean.getBoolean("jsr166.useSecurityManager");
113  
114 +    protected static final boolean expensiveTests =
115 +        Boolean.getBoolean("jsr166.expensiveTests");
116 +
117 +    /**
118 +     * If true, report on stdout all "slow" tests, that is, ones that
119 +     * take more than profileThreshold milliseconds to execute.
120 +     */
121 +    private static final boolean profileTests =
122 +        Boolean.getBoolean("jsr166.profileTests");
123 +
124 +    /**
125 +     * The number of milliseconds that tests are permitted for
126 +     * execution without being reported, when profileTests is set.
127 +     */
128 +    private static final long profileThreshold =
129 +        Long.getLong("jsr166.profileThreshold", 100);
130 +
131 +    protected void runTest() throws Throwable {
132 +        if (profileTests)
133 +            runTestProfiled();
134 +        else
135 +            super.runTest();
136 +    }
137 +
138 +    protected void runTestProfiled() throws Throwable {
139 +        long t0 = System.nanoTime();
140 +        try {
141 +            super.runTest();
142 +        } finally {
143 +            long elapsedMillis =
144 +                (System.nanoTime() - t0) / (1000L * 1000L);
145 +            if (elapsedMillis >= profileThreshold)
146 +                System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
147 +        }
148 +    }
149 +
150      /**
151 <     * Runs all JSR166 unit tests using junit.textui.TestRunner
151 >     * Runs all JSR166 unit tests using junit.textui.TestRunner.
152 >     * Optional command line arg provides the number of iterations to
153 >     * repeat running the tests.
154       */
155      public static void main(String[] args) {
156          if (useSecurityManager) {
# Line 99 | Line 158 | public class JSR166TestCase extends Test
158              Policy.setPolicy(permissivePolicy());
159              System.setSecurityManager(new SecurityManager());
160          }
161 <        int iters = 1;
162 <        if (args.length > 0)
104 <            iters = Integer.parseInt(args[0]);
161 >        int iters = (args.length == 0) ? 1 : Integer.parseInt(args[0]);
162 >
163          Test s = suite();
164          for (int i = 0; i < iters; ++i) {
165              junit.textui.TestRunner.run(s);
# Line 111 | Line 169 | public class JSR166TestCase extends Test
169          System.exit(0);
170      }
171  
172 +    public static TestSuite newTestSuite(Object... suiteOrClasses) {
173 +        TestSuite suite = new TestSuite();
174 +        for (Object suiteOrClass : suiteOrClasses) {
175 +            if (suiteOrClass instanceof TestSuite)
176 +                suite.addTest((TestSuite) suiteOrClass);
177 +            else if (suiteOrClass instanceof Class)
178 +                suite.addTest(new TestSuite((Class<?>) suiteOrClass));
179 +            else
180 +                throw new ClassCastException("not a test suite or class");
181 +        }
182 +        return suite;
183 +    }
184 +
185 +    static void addTestReflectively(TestSuite suite, String testClassName) {
186 +        try {
187 +            Class klazz = Class.forName(testClassName);
188 +            Method m = klazz.getDeclaredMethod("suite", new Class<?>[0]);
189 +            suite.addTest(newTestSuite((Test)m.invoke(null)));
190 +        } catch (Exception e) {
191 +            throw new Error(e);
192 +        }
193 +    }
194 +
195 +    public static final double JAVA_CLASS_VERSION;
196 +    static {
197 +        try {
198 +            JAVA_CLASS_VERSION = java.security.AccessController.doPrivileged(
199 +                new java.security.PrivilegedAction<Double>() {
200 +                public Double run() {
201 +                    return Double.valueOf(System.getProperty("java.class.version"));}});
202 +        } catch (Throwable t) {
203 +            throw new Error(t);
204 +        }
205 +    }
206 +
207 +    public static boolean isAtLeastJdk6() { return JAVA_CLASS_VERSION >= 50.0; }
208 +    public static boolean isAtLeastJdk7() { return JAVA_CLASS_VERSION >= 51.0; }
209 +    public static boolean isAtLeastJdk8() { return JAVA_CLASS_VERSION >= 52.0; }
210 +
211      /**
212 <     * Collects all JSR166 unit tests as one suite
212 >     * Collects all JSR166 unit tests as one suite.
213       */
214      public static Test suite() {
215 <        TestSuite suite = new TestSuite("JSR166 Unit Tests");
216 <
217 <        suite.addTest(new TestSuite(ForkJoinPoolTest.class));
218 <        suite.addTest(new TestSuite(ForkJoinTaskTest.class));
219 <        suite.addTest(new TestSuite(RecursiveActionTest.class));
220 <        suite.addTest(new TestSuite(RecursiveTaskTest.class));
221 <        suite.addTest(new TestSuite(LinkedTransferQueueTest.class));
222 <        suite.addTest(new TestSuite(PhaserTest.class));
223 <        suite.addTest(new TestSuite(ThreadLocalRandomTest.class));
224 <        suite.addTest(new TestSuite(AbstractExecutorServiceTest.class));
225 <        suite.addTest(new TestSuite(AbstractQueueTest.class));
226 <        suite.addTest(new TestSuite(AbstractQueuedSynchronizerTest.class));
227 <        suite.addTest(new TestSuite(AbstractQueuedLongSynchronizerTest.class));
228 <        suite.addTest(new TestSuite(ArrayBlockingQueueTest.class));
229 <        suite.addTest(new TestSuite(ArrayDequeTest.class));
230 <        suite.addTest(new TestSuite(AtomicBooleanTest.class));
231 <        suite.addTest(new TestSuite(AtomicIntegerArrayTest.class));
232 <        suite.addTest(new TestSuite(AtomicIntegerFieldUpdaterTest.class));
233 <        suite.addTest(new TestSuite(AtomicIntegerTest.class));
234 <        suite.addTest(new TestSuite(AtomicLongArrayTest.class));
235 <        suite.addTest(new TestSuite(AtomicLongFieldUpdaterTest.class));
236 <        suite.addTest(new TestSuite(AtomicLongTest.class));
237 <        suite.addTest(new TestSuite(AtomicMarkableReferenceTest.class));
238 <        suite.addTest(new TestSuite(AtomicReferenceArrayTest.class));
239 <        suite.addTest(new TestSuite(AtomicReferenceFieldUpdaterTest.class));
240 <        suite.addTest(new TestSuite(AtomicReferenceTest.class));
241 <        suite.addTest(new TestSuite(AtomicStampedReferenceTest.class));
242 <        suite.addTest(new TestSuite(ConcurrentHashMapTest.class));
243 <        suite.addTest(new TestSuite(ConcurrentLinkedDequeTest.class));
244 <        suite.addTest(new TestSuite(ConcurrentLinkedQueueTest.class));
245 <        suite.addTest(new TestSuite(ConcurrentSkipListMapTest.class));
246 <        suite.addTest(new TestSuite(ConcurrentSkipListSubMapTest.class));
247 <        suite.addTest(new TestSuite(ConcurrentSkipListSetTest.class));
248 <        suite.addTest(new TestSuite(ConcurrentSkipListSubSetTest.class));
249 <        suite.addTest(new TestSuite(CopyOnWriteArrayListTest.class));
250 <        suite.addTest(new TestSuite(CopyOnWriteArraySetTest.class));
251 <        suite.addTest(new TestSuite(CountDownLatchTest.class));
252 <        suite.addTest(new TestSuite(CyclicBarrierTest.class));
253 <        suite.addTest(new TestSuite(DelayQueueTest.class));
254 <        suite.addTest(new TestSuite(EntryTest.class));
255 <        suite.addTest(new TestSuite(ExchangerTest.class));
256 <        suite.addTest(new TestSuite(ExecutorsTest.class));
257 <        suite.addTest(new TestSuite(ExecutorCompletionServiceTest.class));
258 <        suite.addTest(new TestSuite(FutureTaskTest.class));
259 <        suite.addTest(new TestSuite(LinkedBlockingDequeTest.class));
260 <        suite.addTest(new TestSuite(LinkedBlockingQueueTest.class));
261 <        suite.addTest(new TestSuite(LinkedListTest.class));
262 <        suite.addTest(new TestSuite(LockSupportTest.class));
263 <        suite.addTest(new TestSuite(PriorityBlockingQueueTest.class));
264 <        suite.addTest(new TestSuite(PriorityQueueTest.class));
265 <        suite.addTest(new TestSuite(ReentrantLockTest.class));
266 <        suite.addTest(new TestSuite(ReentrantReadWriteLockTest.class));
267 <        suite.addTest(new TestSuite(ScheduledExecutorTest.class));
268 <        suite.addTest(new TestSuite(ScheduledExecutorSubclassTest.class));
269 <        suite.addTest(new TestSuite(SemaphoreTest.class));
270 <        suite.addTest(new TestSuite(SynchronousQueueTest.class));
271 <        suite.addTest(new TestSuite(SystemTest.class));
272 <        suite.addTest(new TestSuite(ThreadLocalTest.class));
273 <        suite.addTest(new TestSuite(ThreadPoolExecutorTest.class));
274 <        suite.addTest(new TestSuite(ThreadPoolExecutorSubclassTest.class));
275 <        suite.addTest(new TestSuite(ThreadTest.class));
276 <        suite.addTest(new TestSuite(TimeUnitTest.class));
277 <        suite.addTest(new TestSuite(TreeMapTest.class));
278 <        suite.addTest(new TestSuite(TreeSetTest.class));
279 <        suite.addTest(new TestSuite(TreeSubMapTest.class));
280 <        suite.addTest(new TestSuite(TreeSubSetTest.class));
281 <
215 >        TestSuite suite = newTestSuite(
216 >            ForkJoinPoolTest.suite(),
217 >            ForkJoinTaskTest.suite(),
218 >            RecursiveActionTest.suite(),
219 >            RecursiveTaskTest.suite(),
220 >            LinkedTransferQueueTest.suite(),
221 >            PhaserTest.suite(),
222 >            ThreadLocalRandomTest.suite(),
223 >            AbstractExecutorServiceTest.suite(),
224 >            AbstractQueueTest.suite(),
225 >            AbstractQueuedSynchronizerTest.suite(),
226 >            AbstractQueuedLongSynchronizerTest.suite(),
227 >            ArrayBlockingQueueTest.suite(),
228 >            ArrayDequeTest.suite(),
229 >            AtomicBooleanTest.suite(),
230 >            AtomicIntegerArrayTest.suite(),
231 >            AtomicIntegerFieldUpdaterTest.suite(),
232 >            AtomicIntegerTest.suite(),
233 >            AtomicLongArrayTest.suite(),
234 >            AtomicLongFieldUpdaterTest.suite(),
235 >            AtomicLongTest.suite(),
236 >            AtomicMarkableReferenceTest.suite(),
237 >            AtomicReferenceArrayTest.suite(),
238 >            AtomicReferenceFieldUpdaterTest.suite(),
239 >            AtomicReferenceTest.suite(),
240 >            AtomicStampedReferenceTest.suite(),
241 >            ConcurrentHashMapTest.suite(),
242 >            ConcurrentLinkedDequeTest.suite(),
243 >            ConcurrentLinkedQueueTest.suite(),
244 >            ConcurrentSkipListMapTest.suite(),
245 >            ConcurrentSkipListSubMapTest.suite(),
246 >            ConcurrentSkipListSetTest.suite(),
247 >            ConcurrentSkipListSubSetTest.suite(),
248 >            CopyOnWriteArrayListTest.suite(),
249 >            CopyOnWriteArraySetTest.suite(),
250 >            CountDownLatchTest.suite(),
251 >            CyclicBarrierTest.suite(),
252 >            DelayQueueTest.suite(),
253 >            EntryTest.suite(),
254 >            ExchangerTest.suite(),
255 >            ExecutorsTest.suite(),
256 >            ExecutorCompletionServiceTest.suite(),
257 >            FutureTaskTest.suite(),
258 >            LinkedBlockingDequeTest.suite(),
259 >            LinkedBlockingQueueTest.suite(),
260 >            LinkedListTest.suite(),
261 >            LockSupportTest.suite(),
262 >            PriorityBlockingQueueTest.suite(),
263 >            PriorityQueueTest.suite(),
264 >            ReentrantLockTest.suite(),
265 >            ReentrantReadWriteLockTest.suite(),
266 >            ScheduledExecutorTest.suite(),
267 >            ScheduledExecutorSubclassTest.suite(),
268 >            SemaphoreTest.suite(),
269 >            SynchronousQueueTest.suite(),
270 >            SystemTest.suite(),
271 >            ThreadLocalTest.suite(),
272 >            ThreadPoolExecutorTest.suite(),
273 >            ThreadPoolExecutorSubclassTest.suite(),
274 >            ThreadTest.suite(),
275 >            TimeUnitTest.suite(),
276 >            TreeMapTest.suite(),
277 >            TreeSetTest.suite(),
278 >            TreeSubMapTest.suite(),
279 >            TreeSubSetTest.suite());
280 >        if (isAtLeastJdk8()) {
281 >            addTestReflectively(suite, "StampedLockTest");
282 >        }
283          return suite;
284      }
285  
# Line 200 | Line 298 | public class JSR166TestCase extends Test
298          return 50;
299      }
300  
203
301      /**
302       * Sets delays as multiples of SHORT_DELAY.
303       */
304      protected void setDelays() {
305          SHORT_DELAY_MS = getShortDelay();
306 <        SMALL_DELAY_MS = SHORT_DELAY_MS * 5;
306 >        SMALL_DELAY_MS  = SHORT_DELAY_MS * 5;
307          MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
308 <        LONG_DELAY_MS = SHORT_DELAY_MS * 50;
308 >        LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
309 >    }
310 >
311 >    /**
312 >     * Returns a timeout in milliseconds to be used in tests that
313 >     * verify that operations block or time out.
314 >     */
315 >    long timeoutMillis() {
316 >        return SHORT_DELAY_MS / 4;
317      }
318  
319      /**
320 <     * Flag set true if any threadAssert methods fail
320 >     * Returns a new Date instance representing a time delayMillis
321 >     * milliseconds in the future.
322       */
323 <    volatile boolean threadFailed;
323 >    Date delayedDate(long delayMillis) {
324 >        return new Date(System.currentTimeMillis() + delayMillis);
325 >    }
326  
327      /**
328 <     * Initializes test to indicate that no thread assertions have failed
328 >     * The first exception encountered if any threadAssertXXX method fails.
329       */
330 +    private final AtomicReference<Throwable> threadFailure
331 +        = new AtomicReference<Throwable>(null);
332 +
333 +    /**
334 +     * Records an exception so that it can be rethrown later in the test
335 +     * harness thread, triggering a test case failure.  Only the first
336 +     * failure is recorded; subsequent calls to this method from within
337 +     * the same test have no effect.
338 +     */
339 +    public void threadRecordFailure(Throwable t) {
340 +        threadFailure.compareAndSet(null, t);
341 +    }
342 +
343      public void setUp() {
344          setDelays();
224        threadFailed = false;
345      }
346  
347      /**
348 <     * Triggers test case failure if any thread assertions have failed
349 <     */
350 <    public void tearDown() {
351 <        assertFalse(threadFailed);
348 >     * Extra checks that get done for all test cases.
349 >     *
350 >     * Triggers test case failure if any thread assertions have failed,
351 >     * by rethrowing, in the test harness thread, any exception recorded
352 >     * earlier by threadRecordFailure.
353 >     *
354 >     * Triggers test case failure if interrupt status is set in the main thread.
355 >     */
356 >    public void tearDown() throws Exception {
357 >        Throwable t = threadFailure.getAndSet(null);
358 >        if (t != null) {
359 >            if (t instanceof Error)
360 >                throw (Error) t;
361 >            else if (t instanceof RuntimeException)
362 >                throw (RuntimeException) t;
363 >            else if (t instanceof Exception)
364 >                throw (Exception) t;
365 >            else {
366 >                AssertionFailedError afe =
367 >                    new AssertionFailedError(t.toString());
368 >                afe.initCause(t);
369 >                throw afe;
370 >            }
371 >        }
372 >
373 >        if (Thread.interrupted())
374 >            throw new AssertionFailedError("interrupt status set in main thread");
375      }
376  
377      /**
378 <     * Fail, also setting status to indicate current testcase should fail
378 >     * Just like fail(reason), but additionally recording (using
379 >     * threadRecordFailure) any AssertionFailedError thrown, so that
380 >     * the current testcase will fail.
381       */
382      public void threadFail(String reason) {
383 <        threadFailed = true;
384 <        fail(reason);
383 >        try {
384 >            fail(reason);
385 >        } catch (AssertionFailedError t) {
386 >            threadRecordFailure(t);
387 >            fail(reason);
388 >        }
389      }
390  
391      /**
392 <     * If expression not true, set status to indicate current testcase
393 <     * should fail
392 >     * Just like assertTrue(b), but additionally recording (using
393 >     * threadRecordFailure) any AssertionFailedError thrown, so that
394 >     * the current testcase will fail.
395       */
396      public void threadAssertTrue(boolean b) {
397 <        if (!b) {
248 <            threadFailed = true;
397 >        try {
398              assertTrue(b);
399 +        } catch (AssertionFailedError t) {
400 +            threadRecordFailure(t);
401 +            throw t;
402          }
403      }
404  
405      /**
406 <     * If expression not false, set status to indicate current testcase
407 <     * should fail
406 >     * Just like assertFalse(b), but additionally recording (using
407 >     * threadRecordFailure) any AssertionFailedError thrown, so that
408 >     * the current testcase will fail.
409       */
410      public void threadAssertFalse(boolean b) {
411 <        if (b) {
259 <            threadFailed = true;
411 >        try {
412              assertFalse(b);
413 +        } catch (AssertionFailedError t) {
414 +            threadRecordFailure(t);
415 +            throw t;
416          }
417      }
418  
419      /**
420 <     * If argument not null, set status to indicate current testcase
421 <     * should fail
420 >     * Just like assertNull(x), but additionally recording (using
421 >     * threadRecordFailure) any AssertionFailedError thrown, so that
422 >     * the current testcase will fail.
423       */
424      public void threadAssertNull(Object x) {
425 <        if (x != null) {
270 <            threadFailed = true;
425 >        try {
426              assertNull(x);
427 +        } catch (AssertionFailedError t) {
428 +            threadRecordFailure(t);
429 +            throw t;
430          }
431      }
432  
433      /**
434 <     * If arguments not equal, set status to indicate current testcase
435 <     * should fail
434 >     * Just like assertEquals(x, y), but additionally recording (using
435 >     * threadRecordFailure) any AssertionFailedError thrown, so that
436 >     * the current testcase will fail.
437       */
438      public void threadAssertEquals(long x, long y) {
439 <        if (x != y) {
281 <            threadFailed = true;
439 >        try {
440              assertEquals(x, y);
441 +        } catch (AssertionFailedError t) {
442 +            threadRecordFailure(t);
443 +            throw t;
444          }
445      }
446  
447      /**
448 <     * If arguments not equal, set status to indicate current testcase
449 <     * should fail
448 >     * Just like assertEquals(x, y), but additionally recording (using
449 >     * threadRecordFailure) any AssertionFailedError thrown, so that
450 >     * the current testcase will fail.
451       */
452      public void threadAssertEquals(Object x, Object y) {
453 <        if (x != y && (x == null || !x.equals(y))) {
292 <            threadFailed = true;
453 >        try {
454              assertEquals(x, y);
455 +        } catch (AssertionFailedError t) {
456 +            threadRecordFailure(t);
457 +            throw t;
458 +        } catch (Throwable t) {
459 +            threadUnexpectedException(t);
460          }
461      }
462  
463      /**
464 <     * threadFail with message "should throw exception"
464 >     * Just like assertSame(x, y), but additionally recording (using
465 >     * threadRecordFailure) any AssertionFailedError thrown, so that
466 >     * the current testcase will fail.
467 >     */
468 >    public void threadAssertSame(Object x, Object y) {
469 >        try {
470 >            assertSame(x, y);
471 >        } catch (AssertionFailedError t) {
472 >            threadRecordFailure(t);
473 >            throw t;
474 >        }
475 >    }
476 >
477 >    /**
478 >     * Calls threadFail with message "should throw exception".
479       */
480      public void threadShouldThrow() {
481 <        threadFailed = true;
302 <        fail("should throw exception");
481 >        threadFail("should throw exception");
482      }
483  
484      /**
485 <     * threadFail with message "should throw" + exceptionName
485 >     * Calls threadFail with message "should throw" + exceptionName.
486       */
487      public void threadShouldThrow(String exceptionName) {
488 <        threadFailed = true;
310 <        fail("should throw " + exceptionName);
488 >        threadFail("should throw " + exceptionName);
489      }
490  
491      /**
492 <     * threadFail with message "Unexpected exception"
492 >     * Records the given exception using {@link #threadRecordFailure},
493 >     * then rethrows the exception, wrapping it in an
494 >     * AssertionFailedError if necessary.
495       */
496 <    public void threadUnexpectedException() {
497 <        threadFailed = true;
498 <        fail("Unexpected exception");
496 >    public void threadUnexpectedException(Throwable t) {
497 >        threadRecordFailure(t);
498 >        t.printStackTrace();
499 >        if (t instanceof RuntimeException)
500 >            throw (RuntimeException) t;
501 >        else if (t instanceof Error)
502 >            throw (Error) t;
503 >        else {
504 >            AssertionFailedError afe =
505 >                new AssertionFailedError("unexpected exception: " + t);
506 >            afe.initCause(t);
507 >            throw afe;
508 >        }
509      }
510  
511      /**
512 <     * threadFail with message "Unexpected exception", with argument
512 >     * Delays, via Thread.sleep, for the given millisecond delay, but
513 >     * if the sleep is shorter than specified, may re-sleep or yield
514 >     * until time elapses.
515       */
516 <    public void threadUnexpectedException(Throwable ex) {
517 <        threadFailed = true;
518 <        ex.printStackTrace();
519 <        fail("Unexpected exception: " + ex);
516 >    static void delay(long millis) throws InterruptedException {
517 >        long startTime = System.nanoTime();
518 >        long ns = millis * 1000 * 1000;
519 >        for (;;) {
520 >            if (millis > 0L)
521 >                Thread.sleep(millis);
522 >            else // too short to sleep
523 >                Thread.yield();
524 >            long d = ns - (System.nanoTime() - startTime);
525 >            if (d > 0L)
526 >                millis = d / (1000 * 1000);
527 >            else
528 >                break;
529 >        }
530      }
531  
532      /**
533 <     * Wait out termination of a thread pool or fail doing so
533 >     * Waits out termination of a thread pool or fails doing so.
534       */
535 <    public void joinPool(ExecutorService exec) {
535 >    void joinPool(ExecutorService exec) {
536          try {
537              exec.shutdown();
538 <            assertTrue(exec.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
538 >            assertTrue("ExecutorService did not terminate in a timely manner",
539 >                       exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS));
540          } catch (SecurityException ok) {
541              // Allowed in case test doesn't have privs
542          } catch (InterruptedException ie) {
# Line 341 | Line 544 | public class JSR166TestCase extends Test
544          }
545      }
546  
547 +    /**
548 +     * A debugging tool to print all stack traces, as jstack does.
549 +     */
550 +    static void printAllStackTraces() {
551 +        for (ThreadInfo info :
552 +                 ManagementFactory.getThreadMXBean()
553 +                 .dumpAllThreads(true, true))
554 +            System.err.print(info);
555 +    }
556  
557      /**
558 <     * fail with message "should throw exception"
558 >     * Checks that thread does not terminate within the default
559 >     * millisecond delay of {@code timeoutMillis()}.
560       */
561 <    public void shouldThrow() {
562 <        fail("Should throw exception");
561 >    void assertThreadStaysAlive(Thread thread) {
562 >        assertThreadStaysAlive(thread, timeoutMillis());
563      }
564  
565      /**
566 <     * fail with message "should throw " + exceptionName
566 >     * Checks that thread does not terminate within the given millisecond delay.
567       */
568 <    public void shouldThrow(String exceptionName) {
569 <        fail("Should throw " + exceptionName);
568 >    void assertThreadStaysAlive(Thread thread, long millis) {
569 >        try {
570 >            // No need to optimize the failing case via Thread.join.
571 >            delay(millis);
572 >            assertTrue(thread.isAlive());
573 >        } catch (InterruptedException ie) {
574 >            fail("Unexpected InterruptedException");
575 >        }
576      }
577  
578      /**
579 <     * fail with message "Unexpected exception"
579 >     * Checks that the threads do not terminate within the default
580 >     * millisecond delay of {@code timeoutMillis()}.
581       */
582 <    public void unexpectedException() {
583 <        fail("Unexpected exception");
582 >    void assertThreadsStayAlive(Thread... threads) {
583 >        assertThreadsStayAlive(timeoutMillis(), threads);
584      }
585  
586      /**
587 <     * fail with message "Unexpected exception", with argument
587 >     * Checks that the threads do not terminate within the given millisecond delay.
588       */
589 <    public void unexpectedException(Throwable ex) {
590 <        ex.printStackTrace();
591 <        fail("Unexpected exception: " + ex);
589 >    void assertThreadsStayAlive(long millis, Thread... threads) {
590 >        try {
591 >            // No need to optimize the failing case via Thread.join.
592 >            delay(millis);
593 >            for (Thread thread : threads)
594 >                assertTrue(thread.isAlive());
595 >        } catch (InterruptedException ie) {
596 >            fail("Unexpected InterruptedException");
597 >        }
598      }
599  
600 +    /**
601 +     * Checks that future.get times out, with the default timeout of
602 +     * {@code timeoutMillis()}.
603 +     */
604 +    void assertFutureTimesOut(Future future) {
605 +        assertFutureTimesOut(future, timeoutMillis());
606 +    }
607 +
608 +    /**
609 +     * Checks that future.get times out, with the given millisecond timeout.
610 +     */
611 +    void assertFutureTimesOut(Future future, long timeoutMillis) {
612 +        long startTime = System.nanoTime();
613 +        try {
614 +            future.get(timeoutMillis, MILLISECONDS);
615 +            shouldThrow();
616 +        } catch (TimeoutException success) {
617 +        } catch (Exception e) {
618 +            threadUnexpectedException(e);
619 +        } finally { future.cancel(true); }
620 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
621 +    }
622 +
623 +    /**
624 +     * Fails with message "should throw exception".
625 +     */
626 +    public void shouldThrow() {
627 +        fail("Should throw exception");
628 +    }
629 +
630 +    /**
631 +     * Fails with message "should throw " + exceptionName.
632 +     */
633 +    public void shouldThrow(String exceptionName) {
634 +        fail("Should throw " + exceptionName);
635 +    }
636  
637      /**
638       * The number of elements to place in collections, arrays, etc.
# Line 409 | Line 671 | public class JSR166TestCase extends Test
671          SecurityManager sm = System.getSecurityManager();
672          if (sm == null) {
673              r.run();
674 +        }
675 +        runWithSecurityManagerWithPermissions(r, permissions);
676 +    }
677 +
678 +    /**
679 +     * Runs Runnable r with a security policy that permits precisely
680 +     * the specified permissions.  If there is no current security
681 +     * manager, a temporary one is set for the duration of the
682 +     * Runnable.  We require that any security manager permit
683 +     * getPolicy/setPolicy.
684 +     */
685 +    public void runWithSecurityManagerWithPermissions(Runnable r,
686 +                                                      Permission... permissions) {
687 +        SecurityManager sm = System.getSecurityManager();
688 +        if (sm == null) {
689              Policy savedPolicy = Policy.getPolicy();
690              try {
691                  Policy.setPolicy(permissivePolicy());
692                  System.setSecurityManager(new SecurityManager());
693 <                runWithPermissions(r, permissions);
693 >                runWithSecurityManagerWithPermissions(r, permissions);
694              } finally {
695                  System.setSecurityManager(null);
696                  Policy.setPolicy(savedPolicy);
# Line 461 | Line 738 | public class JSR166TestCase extends Test
738              return perms.implies(p);
739          }
740          public void refresh() {}
741 +        public String toString() {
742 +            List<Permission> ps = new ArrayList<Permission>();
743 +            for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
744 +                ps.add(e.nextElement());
745 +            return "AdjustablePolicy with permissions " + ps;
746 +        }
747      }
748  
749      /**
# Line 483 | Line 766 | public class JSR166TestCase extends Test
766      }
767  
768      /**
769 <     * Sleep until the timeout has elapsed, or interrupted.
770 <     * Does <em>NOT</em> throw InterruptedException.
769 >     * Sleeps until the given time has elapsed.
770 >     * Throws AssertionFailedError if interrupted.
771       */
772 <    void sleepTillInterrupted(long timeoutMillis) {
772 >    void sleep(long millis) {
773          try {
774 <            Thread.sleep(timeoutMillis);
775 <        } catch (InterruptedException wakeup) {}
774 >            delay(millis);
775 >        } catch (InterruptedException ie) {
776 >            AssertionFailedError afe =
777 >                new AssertionFailedError("Unexpected InterruptedException");
778 >            afe.initCause(ie);
779 >            throw afe;
780 >        }
781 >    }
782 >
783 >    /**
784 >     * Spin-waits up to the specified number of milliseconds for the given
785 >     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
786 >     */
787 >    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
788 >        long startTime = System.nanoTime();
789 >        for (;;) {
790 >            Thread.State s = thread.getState();
791 >            if (s == Thread.State.BLOCKED ||
792 >                s == Thread.State.WAITING ||
793 >                s == Thread.State.TIMED_WAITING)
794 >                return;
795 >            else if (s == Thread.State.TERMINATED)
796 >                fail("Unexpected thread termination");
797 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
798 >                threadAssertTrue(thread.isAlive());
799 >                return;
800 >            }
801 >            Thread.yield();
802 >        }
803 >    }
804 >
805 >    /**
806 >     * Waits up to LONG_DELAY_MS for the given thread to enter a wait
807 >     * state: BLOCKED, WAITING, or TIMED_WAITING.
808 >     */
809 >    void waitForThreadToEnterWaitState(Thread thread) {
810 >        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
811 >    }
812 >
813 >    /**
814 >     * Returns the number of milliseconds since time given by
815 >     * startNanoTime, which must have been previously returned from a
816 >     * call to {@link System.nanoTime()}.
817 >     */
818 >    long millisElapsedSince(long startNanoTime) {
819 >        return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
820      }
821  
822      /**
823 <     * Returns a new started Thread running the given runnable.
823 >     * Returns a new started daemon Thread running the given runnable.
824       */
825      Thread newStartedThread(Runnable runnable) {
826          Thread t = new Thread(runnable);
827 +        t.setDaemon(true);
828          t.start();
829          return t;
830      }
831  
832 +    /**
833 +     * Waits for the specified time (in milliseconds) for the thread
834 +     * to terminate (using {@link Thread#join(long)}), else interrupts
835 +     * the thread (in the hope that it may terminate later) and fails.
836 +     */
837 +    void awaitTermination(Thread t, long timeoutMillis) {
838 +        try {
839 +            t.join(timeoutMillis);
840 +        } catch (InterruptedException ie) {
841 +            threadUnexpectedException(ie);
842 +        } finally {
843 +            if (t.getState() != Thread.State.TERMINATED) {
844 +                t.interrupt();
845 +                fail("Test timed out");
846 +            }
847 +        }
848 +    }
849 +
850 +    /**
851 +     * Waits for LONG_DELAY_MS milliseconds for the thread to
852 +     * terminate (using {@link Thread#join(long)}), else interrupts
853 +     * the thread (in the hope that it may terminate later) and fails.
854 +     */
855 +    void awaitTermination(Thread t) {
856 +        awaitTermination(t, LONG_DELAY_MS);
857 +    }
858 +
859      // Some convenient Runnable classes
860  
861      public abstract class CheckedRunnable implements Runnable {
# Line 563 | Line 918 | public class JSR166TestCase extends Test
918                  realRun();
919                  threadShouldThrow("InterruptedException");
920              } catch (InterruptedException success) {
921 +                threadAssertFalse(Thread.interrupted());
922              } catch (Throwable t) {
923                  threadUnexpectedException(t);
924              }
# Line 577 | Line 933 | public class JSR166TestCase extends Test
933                  return realCall();
934              } catch (Throwable t) {
935                  threadUnexpectedException(t);
936 +                return null;
937              }
581            return null;
938          }
939      }
940  
941 <    public abstract class CheckedInterruptedCallable<T> implements Callable<T> {
941 >    public abstract class CheckedInterruptedCallable<T>
942 >        implements Callable<T> {
943          protected abstract T realCall() throws Throwable;
944  
945          public final T call() {
# Line 591 | Line 948 | public class JSR166TestCase extends Test
948                  threadShouldThrow("InterruptedException");
949                  return result;
950              } catch (InterruptedException success) {
951 +                threadAssertFalse(Thread.interrupted());
952              } catch (Throwable t) {
953                  threadUnexpectedException(t);
954              }
# Line 614 | Line 972 | public class JSR166TestCase extends Test
972  
973      public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
974          return new CheckedCallable<String>() {
975 <            public String realCall() {
975 >            protected String realCall() {
976                  try {
977                      latch.await();
978                  } catch (InterruptedException quittingTime) {}
# Line 622 | Line 980 | public class JSR166TestCase extends Test
980              }};
981      }
982  
983 +    public Runnable awaiter(final CountDownLatch latch) {
984 +        return new CheckedRunnable() {
985 +            public void realRun() throws InterruptedException {
986 +                await(latch);
987 +            }};
988 +    }
989 +
990 +    public void await(CountDownLatch latch) {
991 +        try {
992 +            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
993 +        } catch (Throwable t) {
994 +            threadUnexpectedException(t);
995 +        }
996 +    }
997 +
998 +    public void await(Semaphore semaphore) {
999 +        try {
1000 +            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1001 +        } catch (Throwable t) {
1002 +            threadUnexpectedException(t);
1003 +        }
1004 +    }
1005 +
1006 + //     /**
1007 + //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1008 + //      */
1009 + //     public void await(AtomicBoolean flag) {
1010 + //         await(flag, LONG_DELAY_MS);
1011 + //     }
1012 +
1013 + //     /**
1014 + //      * Spin-waits up to the specified timeout until flag becomes true.
1015 + //      */
1016 + //     public void await(AtomicBoolean flag, long timeoutMillis) {
1017 + //         long startTime = System.nanoTime();
1018 + //         while (!flag.get()) {
1019 + //             if (millisElapsedSince(startTime) > timeoutMillis)
1020 + //                 throw new AssertionFailedError("timed out");
1021 + //             Thread.yield();
1022 + //         }
1023 + //     }
1024 +
1025      public static class NPETask implements Callable<String> {
1026          public String call() { throw new NullPointerException(); }
1027      }
# Line 632 | Line 1032 | public class JSR166TestCase extends Test
1032  
1033      public class ShortRunnable extends CheckedRunnable {
1034          protected void realRun() throws Throwable {
1035 <            Thread.sleep(SHORT_DELAY_MS);
1035 >            delay(SHORT_DELAY_MS);
1036          }
1037      }
1038  
1039      public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1040          protected void realRun() throws InterruptedException {
1041 <            Thread.sleep(SHORT_DELAY_MS);
1041 >            delay(SHORT_DELAY_MS);
1042          }
1043      }
1044  
1045      public class SmallRunnable extends CheckedRunnable {
1046          protected void realRun() throws Throwable {
1047 <            Thread.sleep(SMALL_DELAY_MS);
1047 >            delay(SMALL_DELAY_MS);
1048          }
1049      }
1050  
1051      public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1052          protected void realRun() {
1053              try {
1054 <                Thread.sleep(SMALL_DELAY_MS);
1054 >                delay(SMALL_DELAY_MS);
1055              } catch (InterruptedException ok) {}
1056          }
1057      }
1058  
1059      public class SmallCallable extends CheckedCallable {
1060          protected Object realCall() throws InterruptedException {
1061 <            Thread.sleep(SMALL_DELAY_MS);
1061 >            delay(SMALL_DELAY_MS);
1062              return Boolean.TRUE;
1063          }
1064      }
1065  
666    public class SmallInterruptedRunnable extends CheckedInterruptedRunnable {
667        protected void realRun() throws InterruptedException {
668            Thread.sleep(SMALL_DELAY_MS);
669        }
670    }
671
1066      public class MediumRunnable extends CheckedRunnable {
1067          protected void realRun() throws Throwable {
1068 <            Thread.sleep(MEDIUM_DELAY_MS);
1068 >            delay(MEDIUM_DELAY_MS);
1069          }
1070      }
1071  
1072      public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1073          protected void realRun() throws InterruptedException {
1074 <            Thread.sleep(MEDIUM_DELAY_MS);
1074 >            delay(MEDIUM_DELAY_MS);
1075          }
1076      }
1077  
1078 +    public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1079 +        return new CheckedRunnable() {
1080 +            protected void realRun() {
1081 +                try {
1082 +                    delay(timeoutMillis);
1083 +                } catch (InterruptedException ok) {}
1084 +            }};
1085 +    }
1086 +
1087      public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1088          protected void realRun() {
1089              try {
1090 <                Thread.sleep(MEDIUM_DELAY_MS);
1090 >                delay(MEDIUM_DELAY_MS);
1091              } catch (InterruptedException ok) {}
1092          }
1093      }
# Line 692 | Line 1095 | public class JSR166TestCase extends Test
1095      public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1096          protected void realRun() {
1097              try {
1098 <                Thread.sleep(LONG_DELAY_MS);
1098 >                delay(LONG_DELAY_MS);
1099              } catch (InterruptedException ok) {}
1100          }
1101      }
# Line 706 | Line 1109 | public class JSR166TestCase extends Test
1109          }
1110      }
1111  
1112 +    public interface TrackedRunnable extends Runnable {
1113 +        boolean isDone();
1114 +    }
1115 +
1116 +    public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
1117 +        return new TrackedRunnable() {
1118 +                private volatile boolean done = false;
1119 +                public boolean isDone() { return done; }
1120 +                public void run() {
1121 +                    try {
1122 +                        delay(timeoutMillis);
1123 +                        done = true;
1124 +                    } catch (InterruptedException ok) {}
1125 +                }
1126 +            };
1127 +    }
1128 +
1129      public static class TrackedShortRunnable implements Runnable {
1130          public volatile boolean done = false;
1131          public void run() {
1132              try {
1133 <                Thread.sleep(SMALL_DELAY_MS);
1133 >                delay(SHORT_DELAY_MS);
1134 >                done = true;
1135 >            } catch (InterruptedException ok) {}
1136 >        }
1137 >    }
1138 >
1139 >    public static class TrackedSmallRunnable implements Runnable {
1140 >        public volatile boolean done = false;
1141 >        public void run() {
1142 >            try {
1143 >                delay(SMALL_DELAY_MS);
1144                  done = true;
1145              } catch (InterruptedException ok) {}
1146          }
# Line 720 | Line 1150 | public class JSR166TestCase extends Test
1150          public volatile boolean done = false;
1151          public void run() {
1152              try {
1153 <                Thread.sleep(MEDIUM_DELAY_MS);
1153 >                delay(MEDIUM_DELAY_MS);
1154                  done = true;
1155              } catch (InterruptedException ok) {}
1156          }
# Line 730 | Line 1160 | public class JSR166TestCase extends Test
1160          public volatile boolean done = false;
1161          public void run() {
1162              try {
1163 <                Thread.sleep(LONG_DELAY_MS);
1163 >                delay(LONG_DELAY_MS);
1164                  done = true;
1165              } catch (InterruptedException ok) {}
1166          }
# Line 747 | Line 1177 | public class JSR166TestCase extends Test
1177          public volatile boolean done = false;
1178          public Object call() {
1179              try {
1180 <                Thread.sleep(SMALL_DELAY_MS);
1180 >                delay(SMALL_DELAY_MS);
1181                  done = true;
1182              } catch (InterruptedException ok) {}
1183              return Boolean.TRUE;
1184          }
1185      }
1186  
1187 +    /**
1188 +     * Analog of CheckedRunnable for RecursiveAction
1189 +     */
1190 +    public abstract class CheckedRecursiveAction extends RecursiveAction {
1191 +        protected abstract void realCompute() throws Throwable;
1192 +
1193 +        public final void compute() {
1194 +            try {
1195 +                realCompute();
1196 +            } catch (Throwable t) {
1197 +                threadUnexpectedException(t);
1198 +            }
1199 +        }
1200 +    }
1201 +
1202 +    /**
1203 +     * Analog of CheckedCallable for RecursiveTask
1204 +     */
1205 +    public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1206 +        protected abstract T realCompute() throws Throwable;
1207 +
1208 +        public final T compute() {
1209 +            try {
1210 +                return realCompute();
1211 +            } catch (Throwable t) {
1212 +                threadUnexpectedException(t);
1213 +                return null;
1214 +            }
1215 +        }
1216 +    }
1217  
1218      /**
1219       * For use as RejectedExecutionHandler in constructors
# Line 763 | Line 1223 | public class JSR166TestCase extends Test
1223                                        ThreadPoolExecutor executor) {}
1224      }
1225  
1226 +    /**
1227 +     * A CyclicBarrier that uses timed await and fails with
1228 +     * AssertionFailedErrors instead of throwing checked exceptions.
1229 +     */
1230 +    public class CheckedBarrier extends CyclicBarrier {
1231 +        public CheckedBarrier(int parties) { super(parties); }
1232 +
1233 +        public int await() {
1234 +            try {
1235 +                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1236 +            } catch (TimeoutException e) {
1237 +                throw new AssertionFailedError("timed out");
1238 +            } catch (Exception e) {
1239 +                AssertionFailedError afe =
1240 +                    new AssertionFailedError("Unexpected exception: " + e);
1241 +                afe.initCause(e);
1242 +                throw afe;
1243 +            }
1244 +        }
1245 +    }
1246 +
1247 +    void checkEmpty(BlockingQueue q) {
1248 +        try {
1249 +            assertTrue(q.isEmpty());
1250 +            assertEquals(0, q.size());
1251 +            assertNull(q.peek());
1252 +            assertNull(q.poll());
1253 +            assertNull(q.poll(0, MILLISECONDS));
1254 +            assertEquals(q.toString(), "[]");
1255 +            assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1256 +            assertFalse(q.iterator().hasNext());
1257 +            try {
1258 +                q.element();
1259 +                shouldThrow();
1260 +            } catch (NoSuchElementException success) {}
1261 +            try {
1262 +                q.iterator().next();
1263 +                shouldThrow();
1264 +            } catch (NoSuchElementException success) {}
1265 +            try {
1266 +                q.remove();
1267 +                shouldThrow();
1268 +            } catch (NoSuchElementException success) {}
1269 +        } catch (InterruptedException ie) {
1270 +            threadUnexpectedException(ie);
1271 +        }
1272 +    }
1273 +
1274 +    void assertSerialEquals(Object x, Object y) {
1275 +        assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1276 +    }
1277 +
1278 +    void assertNotSerialEquals(Object x, Object y) {
1279 +        assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1280 +    }
1281 +
1282 +    byte[] serialBytes(Object o) {
1283 +        try {
1284 +            ByteArrayOutputStream bos = new ByteArrayOutputStream();
1285 +            ObjectOutputStream oos = new ObjectOutputStream(bos);
1286 +            oos.writeObject(o);
1287 +            oos.flush();
1288 +            oos.close();
1289 +            return bos.toByteArray();
1290 +        } catch (Throwable t) {
1291 +            threadUnexpectedException(t);
1292 +            return new byte[0];
1293 +        }
1294 +    }
1295 +
1296 +    @SuppressWarnings("unchecked")
1297 +    <T> T serialClone(T o) {
1298 +        try {
1299 +            ObjectInputStream ois = new ObjectInputStream
1300 +                (new ByteArrayInputStream(serialBytes(o)));
1301 +            T clone = (T) ois.readObject();
1302 +            assertSame(o.getClass(), clone.getClass());
1303 +            return clone;
1304 +        } catch (Throwable t) {
1305 +            threadUnexpectedException(t);
1306 +            return null;
1307 +        }
1308 +    }
1309   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines