ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
(Generate patch)

Comparing jsr166/src/test/tck/JSR166TestCase.java (file contents):
Revision 1.54 by jsr166, Fri Sep 17 00:52:36 2010 UTC vs.
Revision 1.100 by jsr166, Wed Feb 6 16:55:50 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.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 static java.util.concurrent.TimeUnit.NANOSECONDS;
29   import java.security.CodeSource;
30   import java.security.Permission;
31   import java.security.PermissionCollection;
# Line 60 | Line 75 | import java.security.SecurityPermission;
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 96 | 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 105 | 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)
110 <            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 117 | 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 +    public static void addNamedTestClasses(TestSuite suite,
186 +                                           String... testClassNames) {
187 +        for (String testClassName : testClassNames) {
188 +            try {
189 +                Class<?> testClass = Class.forName(testClassName);
190 +                Method m = testClass.getDeclaredMethod("suite",
191 +                                                       new Class<?>[0]);
192 +                suite.addTest(newTestSuite((Test)m.invoke(null)));
193 +            } catch (Exception e) {
194 +                throw new Error("Missing test class", e);
195 +            }
196 +        }
197 +    }
198 +
199 +    public static final double JAVA_CLASS_VERSION;
200 +    static {
201 +        try {
202 +            JAVA_CLASS_VERSION = java.security.AccessController.doPrivileged(
203 +                new java.security.PrivilegedAction<Double>() {
204 +                public Double run() {
205 +                    return Double.valueOf(System.getProperty("java.class.version"));}});
206 +        } catch (Throwable t) {
207 +            throw new Error(t);
208 +        }
209 +    }
210 +
211 +    public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
212 +    public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
213 +    public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
214 +
215      /**
216 <     * Collects all JSR166 unit tests as one suite
216 >     * Collects all JSR166 unit tests as one suite.
217       */
218      public static Test suite() {
219 <        TestSuite suite = new TestSuite("JSR166 Unit Tests");
220 <
221 <        suite.addTest(new TestSuite(ForkJoinPoolTest.class));
222 <        suite.addTest(new TestSuite(ForkJoinTaskTest.class));
223 <        suite.addTest(new TestSuite(RecursiveActionTest.class));
224 <        suite.addTest(new TestSuite(RecursiveTaskTest.class));
225 <        suite.addTest(new TestSuite(LinkedTransferQueueTest.class));
226 <        suite.addTest(new TestSuite(PhaserTest.class));
227 <        suite.addTest(new TestSuite(ThreadLocalRandomTest.class));
228 <        suite.addTest(new TestSuite(AbstractExecutorServiceTest.class));
229 <        suite.addTest(new TestSuite(AbstractQueueTest.class));
230 <        suite.addTest(new TestSuite(AbstractQueuedSynchronizerTest.class));
231 <        suite.addTest(new TestSuite(AbstractQueuedLongSynchronizerTest.class));
232 <        suite.addTest(new TestSuite(ArrayBlockingQueueTest.class));
233 <        suite.addTest(new TestSuite(ArrayDequeTest.class));
234 <        suite.addTest(new TestSuite(AtomicBooleanTest.class));
235 <        suite.addTest(new TestSuite(AtomicIntegerArrayTest.class));
236 <        suite.addTest(new TestSuite(AtomicIntegerFieldUpdaterTest.class));
237 <        suite.addTest(new TestSuite(AtomicIntegerTest.class));
238 <        suite.addTest(new TestSuite(AtomicLongArrayTest.class));
239 <        suite.addTest(new TestSuite(AtomicLongFieldUpdaterTest.class));
240 <        suite.addTest(new TestSuite(AtomicLongTest.class));
241 <        suite.addTest(new TestSuite(AtomicMarkableReferenceTest.class));
242 <        suite.addTest(new TestSuite(AtomicReferenceArrayTest.class));
243 <        suite.addTest(new TestSuite(AtomicReferenceFieldUpdaterTest.class));
244 <        suite.addTest(new TestSuite(AtomicReferenceTest.class));
245 <        suite.addTest(new TestSuite(AtomicStampedReferenceTest.class));
246 <        suite.addTest(new TestSuite(ConcurrentHashMapTest.class));
247 <        suite.addTest(new TestSuite(ConcurrentLinkedDequeTest.class));
248 <        suite.addTest(new TestSuite(ConcurrentLinkedQueueTest.class));
249 <        suite.addTest(new TestSuite(ConcurrentSkipListMapTest.class));
250 <        suite.addTest(new TestSuite(ConcurrentSkipListSubMapTest.class));
251 <        suite.addTest(new TestSuite(ConcurrentSkipListSetTest.class));
252 <        suite.addTest(new TestSuite(ConcurrentSkipListSubSetTest.class));
253 <        suite.addTest(new TestSuite(CopyOnWriteArrayListTest.class));
254 <        suite.addTest(new TestSuite(CopyOnWriteArraySetTest.class));
255 <        suite.addTest(new TestSuite(CountDownLatchTest.class));
256 <        suite.addTest(new TestSuite(CyclicBarrierTest.class));
257 <        suite.addTest(new TestSuite(DelayQueueTest.class));
258 <        suite.addTest(new TestSuite(EntryTest.class));
259 <        suite.addTest(new TestSuite(ExchangerTest.class));
260 <        suite.addTest(new TestSuite(ExecutorsTest.class));
261 <        suite.addTest(new TestSuite(ExecutorCompletionServiceTest.class));
262 <        suite.addTest(new TestSuite(FutureTaskTest.class));
263 <        suite.addTest(new TestSuite(LinkedBlockingDequeTest.class));
264 <        suite.addTest(new TestSuite(LinkedBlockingQueueTest.class));
265 <        suite.addTest(new TestSuite(LinkedListTest.class));
266 <        suite.addTest(new TestSuite(LockSupportTest.class));
267 <        suite.addTest(new TestSuite(PriorityBlockingQueueTest.class));
268 <        suite.addTest(new TestSuite(PriorityQueueTest.class));
269 <        suite.addTest(new TestSuite(ReentrantLockTest.class));
270 <        suite.addTest(new TestSuite(ReentrantReadWriteLockTest.class));
271 <        suite.addTest(new TestSuite(ScheduledExecutorTest.class));
272 <        suite.addTest(new TestSuite(ScheduledExecutorSubclassTest.class));
273 <        suite.addTest(new TestSuite(SemaphoreTest.class));
274 <        suite.addTest(new TestSuite(SynchronousQueueTest.class));
275 <        suite.addTest(new TestSuite(SystemTest.class));
276 <        suite.addTest(new TestSuite(ThreadLocalTest.class));
277 <        suite.addTest(new TestSuite(ThreadPoolExecutorTest.class));
278 <        suite.addTest(new TestSuite(ThreadPoolExecutorSubclassTest.class));
279 <        suite.addTest(new TestSuite(ThreadTest.class));
280 <        suite.addTest(new TestSuite(TimeUnitTest.class));
281 <        suite.addTest(new TestSuite(TreeMapTest.class));
282 <        suite.addTest(new TestSuite(TreeSetTest.class));
283 <        suite.addTest(new TestSuite(TreeSubMapTest.class));
284 <        suite.addTest(new TestSuite(TreeSubSetTest.class));
219 >        // Java7+ test classes
220 >        TestSuite suite = newTestSuite(
221 >            ForkJoinPoolTest.suite(),
222 >            ForkJoinTaskTest.suite(),
223 >            RecursiveActionTest.suite(),
224 >            RecursiveTaskTest.suite(),
225 >            LinkedTransferQueueTest.suite(),
226 >            PhaserTest.suite(),
227 >            ThreadLocalRandomTest.suite(),
228 >            AbstractExecutorServiceTest.suite(),
229 >            AbstractQueueTest.suite(),
230 >            AbstractQueuedSynchronizerTest.suite(),
231 >            AbstractQueuedLongSynchronizerTest.suite(),
232 >            ArrayBlockingQueueTest.suite(),
233 >            ArrayDequeTest.suite(),
234 >            AtomicBooleanTest.suite(),
235 >            AtomicIntegerArrayTest.suite(),
236 >            AtomicIntegerFieldUpdaterTest.suite(),
237 >            AtomicIntegerTest.suite(),
238 >            AtomicLongArrayTest.suite(),
239 >            AtomicLongFieldUpdaterTest.suite(),
240 >            AtomicLongTest.suite(),
241 >            AtomicMarkableReferenceTest.suite(),
242 >            AtomicReferenceArrayTest.suite(),
243 >            AtomicReferenceFieldUpdaterTest.suite(),
244 >            AtomicReferenceTest.suite(),
245 >            AtomicStampedReferenceTest.suite(),
246 >            ConcurrentHashMapTest.suite(),
247 >            ConcurrentLinkedDequeTest.suite(),
248 >            ConcurrentLinkedQueueTest.suite(),
249 >            ConcurrentSkipListMapTest.suite(),
250 >            ConcurrentSkipListSubMapTest.suite(),
251 >            ConcurrentSkipListSetTest.suite(),
252 >            ConcurrentSkipListSubSetTest.suite(),
253 >            CopyOnWriteArrayListTest.suite(),
254 >            CopyOnWriteArraySetTest.suite(),
255 >            CountDownLatchTest.suite(),
256 >            CyclicBarrierTest.suite(),
257 >            DelayQueueTest.suite(),
258 >            EntryTest.suite(),
259 >            ExchangerTest.suite(),
260 >            ExecutorsTest.suite(),
261 >            ExecutorCompletionServiceTest.suite(),
262 >            FutureTaskTest.suite(),
263 >            LinkedBlockingDequeTest.suite(),
264 >            LinkedBlockingQueueTest.suite(),
265 >            LinkedListTest.suite(),
266 >            LockSupportTest.suite(),
267 >            PriorityBlockingQueueTest.suite(),
268 >            PriorityQueueTest.suite(),
269 >            ReentrantLockTest.suite(),
270 >            ReentrantReadWriteLockTest.suite(),
271 >            ScheduledExecutorTest.suite(),
272 >            ScheduledExecutorSubclassTest.suite(),
273 >            SemaphoreTest.suite(),
274 >            SynchronousQueueTest.suite(),
275 >            SystemTest.suite(),
276 >            ThreadLocalTest.suite(),
277 >            ThreadPoolExecutorTest.suite(),
278 >            ThreadPoolExecutorSubclassTest.suite(),
279 >            ThreadTest.suite(),
280 >            TimeUnitTest.suite(),
281 >            TreeMapTest.suite(),
282 >            TreeSetTest.suite(),
283 >            TreeSubMapTest.suite(),
284 >            TreeSubSetTest.suite());
285 >
286 >        // Java8+ test classes
287 >        if (atLeastJava8()) {
288 >            String[] java8TestClassNames = {
289 >                "StampedLockTest",
290 >                "ForkJoinPool8Test",
291 >            };
292 >            addNamedTestClasses(suite, java8TestClassNames);
293 >        }
294  
295          return suite;
296      }
# Line 206 | Line 310 | public class JSR166TestCase extends Test
310          return 50;
311      }
312  
209
313      /**
314       * Sets delays as multiples of SHORT_DELAY.
315       */
# Line 214 | Line 317 | public class JSR166TestCase extends Test
317          SHORT_DELAY_MS = getShortDelay();
318          SMALL_DELAY_MS  = SHORT_DELAY_MS * 5;
319          MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
320 <        LONG_DELAY_MS   = SHORT_DELAY_MS * 50;
320 >        LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
321 >    }
322 >
323 >    /**
324 >     * Returns a timeout in milliseconds to be used in tests that
325 >     * verify that operations block or time out.
326 >     */
327 >    long timeoutMillis() {
328 >        return SHORT_DELAY_MS / 4;
329 >    }
330 >
331 >    /**
332 >     * Returns a new Date instance representing a time delayMillis
333 >     * milliseconds in the future.
334 >     */
335 >    Date delayedDate(long delayMillis) {
336 >        return new Date(System.currentTimeMillis() + delayMillis);
337      }
338  
339      /**
# Line 238 | Line 357 | public class JSR166TestCase extends Test
357      }
358  
359      /**
360 +     * Extra checks that get done for all test cases.
361 +     *
362       * Triggers test case failure if any thread assertions have failed,
363       * by rethrowing, in the test harness thread, any exception recorded
364       * earlier by threadRecordFailure.
365 +     *
366 +     * Triggers test case failure if interrupt status is set in the main thread.
367       */
368      public void tearDown() throws Exception {
369 <        Throwable t = threadFailure.get();
369 >        Throwable t = threadFailure.getAndSet(null);
370          if (t != null) {
371              if (t instanceof Error)
372                  throw (Error) t;
# Line 251 | Line 374 | public class JSR166TestCase extends Test
374                  throw (RuntimeException) t;
375              else if (t instanceof Exception)
376                  throw (Exception) t;
377 <            else
378 <                throw new AssertionError(t);
377 >            else {
378 >                AssertionFailedError afe =
379 >                    new AssertionFailedError(t.toString());
380 >                afe.initCause(t);
381 >                throw afe;
382 >            }
383          }
384 +
385 +        if (Thread.interrupted())
386 +            throw new AssertionFailedError("interrupt status set in main thread");
387 +
388 +        checkForkJoinPoolThreadLeaks();
389      }
390  
391      /**
392 +     * Find missing try { ... } finally { joinPool(e); }
393 +     */
394 +    void checkForkJoinPoolThreadLeaks() throws InterruptedException {
395 +        Thread[] survivors = new Thread[5];
396 +        int count = Thread.enumerate(survivors);
397 +        for (int i = 0; i < count; i++) {
398 +            Thread thread = survivors[i];
399 +            String name = thread.getName();
400 +            if (name.startsWith("ForkJoinPool-")) {
401 +                // give thread some time to terminate
402 +                thread.join(LONG_DELAY_MS);
403 +                if (!thread.isAlive()) continue;
404 +                thread.stop();
405 +                throw new AssertionFailedError
406 +                    (String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n",
407 +                                   toString(), name));
408 +            }
409 +        }
410 +    }
411 +        
412 +    /**
413       * Just like fail(reason), but additionally recording (using
414 <     * threadRecordFailure) any AssertionError thrown, so that the current
415 <     * testcase will fail.
414 >     * threadRecordFailure) any AssertionFailedError thrown, so that
415 >     * the current testcase will fail.
416       */
417      public void threadFail(String reason) {
418          try {
419              fail(reason);
420 <        } catch (Throwable t) {
420 >        } catch (AssertionFailedError t) {
421              threadRecordFailure(t);
422              fail(reason);
423          }
# Line 272 | Line 425 | public class JSR166TestCase extends Test
425  
426      /**
427       * Just like assertTrue(b), but additionally recording (using
428 <     * threadRecordFailure) any AssertionError thrown, so that the current
429 <     * testcase will fail.
428 >     * threadRecordFailure) any AssertionFailedError thrown, so that
429 >     * the current testcase will fail.
430       */
431      public void threadAssertTrue(boolean b) {
432          try {
433              assertTrue(b);
434 <        } catch (AssertionError t) {
434 >        } catch (AssertionFailedError t) {
435              threadRecordFailure(t);
436              throw t;
437          }
# Line 286 | Line 439 | public class JSR166TestCase extends Test
439  
440      /**
441       * Just like assertFalse(b), but additionally recording (using
442 <     * threadRecordFailure) any AssertionError thrown, so that the
443 <     * current testcase will fail.
442 >     * threadRecordFailure) any AssertionFailedError thrown, so that
443 >     * the current testcase will fail.
444       */
445      public void threadAssertFalse(boolean b) {
446          try {
447              assertFalse(b);
448 <        } catch (AssertionError t) {
448 >        } catch (AssertionFailedError t) {
449              threadRecordFailure(t);
450              throw t;
451          }
# Line 300 | Line 453 | public class JSR166TestCase extends Test
453  
454      /**
455       * Just like assertNull(x), but additionally recording (using
456 <     * threadRecordFailure) any AssertionError thrown, so that the
457 <     * current testcase will fail.
456 >     * threadRecordFailure) any AssertionFailedError thrown, so that
457 >     * the current testcase will fail.
458       */
459      public void threadAssertNull(Object x) {
460          try {
461              assertNull(x);
462 <        } catch (AssertionError t) {
462 >        } catch (AssertionFailedError t) {
463              threadRecordFailure(t);
464              throw t;
465          }
# Line 314 | Line 467 | public class JSR166TestCase extends Test
467  
468      /**
469       * Just like assertEquals(x, y), but additionally recording (using
470 <     * threadRecordFailure) any AssertionError thrown, so that the
471 <     * current testcase will fail.
470 >     * threadRecordFailure) any AssertionFailedError thrown, so that
471 >     * the current testcase will fail.
472       */
473      public void threadAssertEquals(long x, long y) {
474          try {
475              assertEquals(x, y);
476 <        } catch (AssertionError t) {
476 >        } catch (AssertionFailedError t) {
477              threadRecordFailure(t);
478              throw t;
479          }
# Line 328 | Line 481 | public class JSR166TestCase extends Test
481  
482      /**
483       * Just like assertEquals(x, y), but additionally recording (using
484 <     * threadRecordFailure) any AssertionError thrown, so that the
485 <     * current testcase will fail.
484 >     * threadRecordFailure) any AssertionFailedError thrown, so that
485 >     * the current testcase will fail.
486       */
487      public void threadAssertEquals(Object x, Object y) {
488          try {
489              assertEquals(x, y);
490 <        } catch (AssertionError t) {
490 >        } catch (AssertionFailedError t) {
491              threadRecordFailure(t);
492              throw t;
493 +        } catch (Throwable t) {
494 +            threadUnexpectedException(t);
495          }
496      }
497  
498      /**
499       * Just like assertSame(x, y), but additionally recording (using
500 <     * threadRecordFailure) any AssertionError thrown, so that the
501 <     * current testcase will fail.
500 >     * threadRecordFailure) any AssertionFailedError thrown, so that
501 >     * the current testcase will fail.
502       */
503      public void threadAssertSame(Object x, Object y) {
504          try {
505              assertSame(x, y);
506 <        } catch (AssertionError t) {
506 >        } catch (AssertionFailedError t) {
507              threadRecordFailure(t);
508              throw t;
509          }
# Line 369 | Line 524 | public class JSR166TestCase extends Test
524      }
525  
526      /**
527 <     * Calls threadFail with message "Unexpected exception" + ex.
527 >     * Records the given exception using {@link #threadRecordFailure},
528 >     * then rethrows the exception, wrapping it in an
529 >     * AssertionFailedError if necessary.
530       */
531      public void threadUnexpectedException(Throwable t) {
532          threadRecordFailure(t);
533          t.printStackTrace();
377        // Rethrow, wrapping in an AssertionError if necessary
534          if (t instanceof RuntimeException)
535              throw (RuntimeException) t;
536          else if (t instanceof Error)
537              throw (Error) t;
538          else {
539 <            AssertionError ae = new AssertionError("unexpected exception: " + t);
540 <            t.initCause(t);
541 <            throw ae;
542 <        }            
539 >            AssertionFailedError afe =
540 >                new AssertionFailedError("unexpected exception: " + t);
541 >            afe.initCause(t);
542 >            throw afe;
543 >        }
544 >    }
545 >
546 >    /**
547 >     * Delays, via Thread.sleep, for the given millisecond delay, but
548 >     * if the sleep is shorter than specified, may re-sleep or yield
549 >     * until time elapses.
550 >     */
551 >    static void delay(long millis) throws InterruptedException {
552 >        long startTime = System.nanoTime();
553 >        long ns = millis * 1000 * 1000;
554 >        for (;;) {
555 >            if (millis > 0L)
556 >                Thread.sleep(millis);
557 >            else // too short to sleep
558 >                Thread.yield();
559 >            long d = ns - (System.nanoTime() - startTime);
560 >            if (d > 0L)
561 >                millis = d / (1000 * 1000);
562 >            else
563 >                break;
564 >        }
565      }
566  
567      /**
568       * Waits out termination of a thread pool or fails doing so.
569       */
570 <    public void joinPool(ExecutorService exec) {
570 >    void joinPool(ExecutorService exec) {
571          try {
572              exec.shutdown();
573              assertTrue("ExecutorService did not terminate in a timely manner",
574 <                       exec.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
574 >                       exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS));
575          } catch (SecurityException ok) {
576              // Allowed in case test doesn't have privs
577          } catch (InterruptedException ie) {
# Line 401 | Line 579 | public class JSR166TestCase extends Test
579          }
580      }
581  
582 +    /**
583 +     * A debugging tool to print all stack traces, as jstack does.
584 +     */
585 +    static void printAllStackTraces() {
586 +        for (ThreadInfo info :
587 +                 ManagementFactory.getThreadMXBean()
588 +                 .dumpAllThreads(true, true))
589 +            System.err.print(info);
590 +    }
591 +
592 +    /**
593 +     * Checks that thread does not terminate within the default
594 +     * millisecond delay of {@code timeoutMillis()}.
595 +     */
596 +    void assertThreadStaysAlive(Thread thread) {
597 +        assertThreadStaysAlive(thread, timeoutMillis());
598 +    }
599 +
600 +    /**
601 +     * Checks that thread does not terminate within the given millisecond delay.
602 +     */
603 +    void assertThreadStaysAlive(Thread thread, long millis) {
604 +        try {
605 +            // No need to optimize the failing case via Thread.join.
606 +            delay(millis);
607 +            assertTrue(thread.isAlive());
608 +        } catch (InterruptedException ie) {
609 +            fail("Unexpected InterruptedException");
610 +        }
611 +    }
612 +
613 +    /**
614 +     * Checks that the threads do not terminate within the default
615 +     * millisecond delay of {@code timeoutMillis()}.
616 +     */
617 +    void assertThreadsStayAlive(Thread... threads) {
618 +        assertThreadsStayAlive(timeoutMillis(), threads);
619 +    }
620 +
621 +    /**
622 +     * Checks that the threads do not terminate within the given millisecond delay.
623 +     */
624 +    void assertThreadsStayAlive(long millis, Thread... threads) {
625 +        try {
626 +            // No need to optimize the failing case via Thread.join.
627 +            delay(millis);
628 +            for (Thread thread : threads)
629 +                assertTrue(thread.isAlive());
630 +        } catch (InterruptedException ie) {
631 +            fail("Unexpected InterruptedException");
632 +        }
633 +    }
634 +
635 +    /**
636 +     * Checks that future.get times out, with the default timeout of
637 +     * {@code timeoutMillis()}.
638 +     */
639 +    void assertFutureTimesOut(Future future) {
640 +        assertFutureTimesOut(future, timeoutMillis());
641 +    }
642 +
643 +    /**
644 +     * Checks that future.get times out, with the given millisecond timeout.
645 +     */
646 +    void assertFutureTimesOut(Future future, long timeoutMillis) {
647 +        long startTime = System.nanoTime();
648 +        try {
649 +            future.get(timeoutMillis, MILLISECONDS);
650 +            shouldThrow();
651 +        } catch (TimeoutException success) {
652 +        } catch (Exception e) {
653 +            threadUnexpectedException(e);
654 +        } finally { future.cancel(true); }
655 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
656 +    }
657  
658      /**
659       * Fails with message "should throw exception".
# Line 417 | Line 670 | public class JSR166TestCase extends Test
670      }
671  
672      /**
420     * Fails with message "Unexpected exception: " + ex.
421     */
422    public void unexpectedException(Throwable ex) {
423        ex.printStackTrace();
424        fail("Unexpected exception: " + ex);
425    }
426
427
428    /**
673       * The number of elements to place in collections, arrays, etc.
674       */
675      public static final int SIZE = 20;
# Line 462 | Line 706 | public class JSR166TestCase extends Test
706          SecurityManager sm = System.getSecurityManager();
707          if (sm == null) {
708              r.run();
709 +        }
710 +        runWithSecurityManagerWithPermissions(r, permissions);
711 +    }
712 +
713 +    /**
714 +     * Runs Runnable r with a security policy that permits precisely
715 +     * the specified permissions.  If there is no current security
716 +     * manager, a temporary one is set for the duration of the
717 +     * Runnable.  We require that any security manager permit
718 +     * getPolicy/setPolicy.
719 +     */
720 +    public void runWithSecurityManagerWithPermissions(Runnable r,
721 +                                                      Permission... permissions) {
722 +        SecurityManager sm = System.getSecurityManager();
723 +        if (sm == null) {
724              Policy savedPolicy = Policy.getPolicy();
725              try {
726                  Policy.setPolicy(permissivePolicy());
727                  System.setSecurityManager(new SecurityManager());
728 <                runWithPermissions(r, permissions);
728 >                runWithSecurityManagerWithPermissions(r, permissions);
729              } finally {
730                  System.setSecurityManager(null);
731                  Policy.setPolicy(savedPolicy);
# Line 514 | Line 773 | public class JSR166TestCase extends Test
773              return perms.implies(p);
774          }
775          public void refresh() {}
776 +        public String toString() {
777 +            List<Permission> ps = new ArrayList<Permission>();
778 +            for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
779 +                ps.add(e.nextElement());
780 +            return "AdjustablePolicy with permissions " + ps;
781 +        }
782      }
783  
784      /**
# Line 536 | Line 801 | public class JSR166TestCase extends Test
801      }
802  
803      /**
804 <     * Sleep until the timeout has elapsed, or interrupted.
805 <     * Does <em>NOT</em> throw InterruptedException.
804 >     * Sleeps until the given time has elapsed.
805 >     * Throws AssertionFailedError if interrupted.
806       */
807 <    void sleepTillInterrupted(long timeoutMillis) {
807 >    void sleep(long millis) {
808          try {
809 <            Thread.sleep(timeoutMillis);
810 <        } catch (InterruptedException wakeup) {}
809 >            delay(millis);
810 >        } catch (InterruptedException ie) {
811 >            AssertionFailedError afe =
812 >                new AssertionFailedError("Unexpected InterruptedException");
813 >            afe.initCause(ie);
814 >            throw afe;
815 >        }
816      }
817  
818      /**
819 <     * Returns a new started Thread running the given runnable.
819 >     * Spin-waits up to the specified number of milliseconds for the given
820 >     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
821 >     */
822 >    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
823 >        long startTime = System.nanoTime();
824 >        for (;;) {
825 >            Thread.State s = thread.getState();
826 >            if (s == Thread.State.BLOCKED ||
827 >                s == Thread.State.WAITING ||
828 >                s == Thread.State.TIMED_WAITING)
829 >                return;
830 >            else if (s == Thread.State.TERMINATED)
831 >                fail("Unexpected thread termination");
832 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
833 >                threadAssertTrue(thread.isAlive());
834 >                return;
835 >            }
836 >            Thread.yield();
837 >        }
838 >    }
839 >
840 >    /**
841 >     * Waits up to LONG_DELAY_MS for the given thread to enter a wait
842 >     * state: BLOCKED, WAITING, or TIMED_WAITING.
843 >     */
844 >    void waitForThreadToEnterWaitState(Thread thread) {
845 >        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
846 >    }
847 >
848 >    /**
849 >     * Returns the number of milliseconds since time given by
850 >     * startNanoTime, which must have been previously returned from a
851 >     * call to {@link System.nanoTime()}.
852 >     */
853 >    long millisElapsedSince(long startNanoTime) {
854 >        return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
855 >    }
856 >
857 >    /**
858 >     * Returns a new started daemon Thread running the given runnable.
859       */
860      Thread newStartedThread(Runnable runnable) {
861          Thread t = new Thread(runnable);
862 +        t.setDaemon(true);
863          t.start();
864          return t;
865      }
866  
867 +    /**
868 +     * Waits for the specified time (in milliseconds) for the thread
869 +     * to terminate (using {@link Thread#join(long)}), else interrupts
870 +     * the thread (in the hope that it may terminate later) and fails.
871 +     */
872 +    void awaitTermination(Thread t, long timeoutMillis) {
873 +        try {
874 +            t.join(timeoutMillis);
875 +        } catch (InterruptedException ie) {
876 +            threadUnexpectedException(ie);
877 +        } finally {
878 +            if (t.getState() != Thread.State.TERMINATED) {
879 +                t.interrupt();
880 +                fail("Test timed out");
881 +            }
882 +        }
883 +    }
884 +
885 +    /**
886 +     * Waits for LONG_DELAY_MS milliseconds for the thread to
887 +     * terminate (using {@link Thread#join(long)}), else interrupts
888 +     * the thread (in the hope that it may terminate later) and fails.
889 +     */
890 +    void awaitTermination(Thread t) {
891 +        awaitTermination(t, LONG_DELAY_MS);
892 +    }
893 +
894      // Some convenient Runnable classes
895  
896      public abstract class CheckedRunnable implements Runnable {
# Line 616 | Line 953 | public class JSR166TestCase extends Test
953                  realRun();
954                  threadShouldThrow("InterruptedException");
955              } catch (InterruptedException success) {
956 +                threadAssertFalse(Thread.interrupted());
957              } catch (Throwable t) {
958                  threadUnexpectedException(t);
959              }
# Line 645 | Line 983 | public class JSR166TestCase extends Test
983                  threadShouldThrow("InterruptedException");
984                  return result;
985              } catch (InterruptedException success) {
986 +                threadAssertFalse(Thread.interrupted());
987              } catch (Throwable t) {
988                  threadUnexpectedException(t);
989              }
# Line 668 | Line 1007 | public class JSR166TestCase extends Test
1007  
1008      public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
1009          return new CheckedCallable<String>() {
1010 <            public String realCall() {
1010 >            protected String realCall() {
1011                  try {
1012                      latch.await();
1013                  } catch (InterruptedException quittingTime) {}
# Line 676 | Line 1015 | public class JSR166TestCase extends Test
1015              }};
1016      }
1017  
1018 +    public Runnable awaiter(final CountDownLatch latch) {
1019 +        return new CheckedRunnable() {
1020 +            public void realRun() throws InterruptedException {
1021 +                await(latch);
1022 +            }};
1023 +    }
1024 +
1025 +    public void await(CountDownLatch latch) {
1026 +        try {
1027 +            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1028 +        } catch (Throwable t) {
1029 +            threadUnexpectedException(t);
1030 +        }
1031 +    }
1032 +
1033 +    public void await(Semaphore semaphore) {
1034 +        try {
1035 +            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1036 +        } catch (Throwable t) {
1037 +            threadUnexpectedException(t);
1038 +        }
1039 +    }
1040 +
1041 + //     /**
1042 + //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1043 + //      */
1044 + //     public void await(AtomicBoolean flag) {
1045 + //         await(flag, LONG_DELAY_MS);
1046 + //     }
1047 +
1048 + //     /**
1049 + //      * Spin-waits up to the specified timeout until flag becomes true.
1050 + //      */
1051 + //     public void await(AtomicBoolean flag, long timeoutMillis) {
1052 + //         long startTime = System.nanoTime();
1053 + //         while (!flag.get()) {
1054 + //             if (millisElapsedSince(startTime) > timeoutMillis)
1055 + //                 throw new AssertionFailedError("timed out");
1056 + //             Thread.yield();
1057 + //         }
1058 + //     }
1059 +
1060      public static class NPETask implements Callable<String> {
1061          public String call() { throw new NullPointerException(); }
1062      }
# Line 686 | Line 1067 | public class JSR166TestCase extends Test
1067  
1068      public class ShortRunnable extends CheckedRunnable {
1069          protected void realRun() throws Throwable {
1070 <            Thread.sleep(SHORT_DELAY_MS);
1070 >            delay(SHORT_DELAY_MS);
1071          }
1072      }
1073  
1074      public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1075          protected void realRun() throws InterruptedException {
1076 <            Thread.sleep(SHORT_DELAY_MS);
1076 >            delay(SHORT_DELAY_MS);
1077          }
1078      }
1079  
1080      public class SmallRunnable extends CheckedRunnable {
1081          protected void realRun() throws Throwable {
1082 <            Thread.sleep(SMALL_DELAY_MS);
1082 >            delay(SMALL_DELAY_MS);
1083          }
1084      }
1085  
1086      public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1087          protected void realRun() {
1088              try {
1089 <                Thread.sleep(SMALL_DELAY_MS);
1089 >                delay(SMALL_DELAY_MS);
1090              } catch (InterruptedException ok) {}
1091          }
1092      }
1093  
1094      public class SmallCallable extends CheckedCallable {
1095          protected Object realCall() throws InterruptedException {
1096 <            Thread.sleep(SMALL_DELAY_MS);
1096 >            delay(SMALL_DELAY_MS);
1097              return Boolean.TRUE;
1098          }
1099      }
1100  
720    public class SmallInterruptedRunnable extends CheckedInterruptedRunnable {
721        protected void realRun() throws InterruptedException {
722            Thread.sleep(SMALL_DELAY_MS);
723        }
724    }
725
1101      public class MediumRunnable extends CheckedRunnable {
1102          protected void realRun() throws Throwable {
1103 <            Thread.sleep(MEDIUM_DELAY_MS);
1103 >            delay(MEDIUM_DELAY_MS);
1104          }
1105      }
1106  
1107      public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1108          protected void realRun() throws InterruptedException {
1109 <            Thread.sleep(MEDIUM_DELAY_MS);
1109 >            delay(MEDIUM_DELAY_MS);
1110          }
1111      }
1112  
1113 +    public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1114 +        return new CheckedRunnable() {
1115 +            protected void realRun() {
1116 +                try {
1117 +                    delay(timeoutMillis);
1118 +                } catch (InterruptedException ok) {}
1119 +            }};
1120 +    }
1121 +
1122      public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1123          protected void realRun() {
1124              try {
1125 <                Thread.sleep(MEDIUM_DELAY_MS);
1125 >                delay(MEDIUM_DELAY_MS);
1126              } catch (InterruptedException ok) {}
1127          }
1128      }
# Line 746 | Line 1130 | public class JSR166TestCase extends Test
1130      public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1131          protected void realRun() {
1132              try {
1133 <                Thread.sleep(LONG_DELAY_MS);
1133 >                delay(LONG_DELAY_MS);
1134              } catch (InterruptedException ok) {}
1135          }
1136      }
# Line 760 | Line 1144 | public class JSR166TestCase extends Test
1144          }
1145      }
1146  
1147 +    public interface TrackedRunnable extends Runnable {
1148 +        boolean isDone();
1149 +    }
1150 +
1151 +    public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
1152 +        return new TrackedRunnable() {
1153 +                private volatile boolean done = false;
1154 +                public boolean isDone() { return done; }
1155 +                public void run() {
1156 +                    try {
1157 +                        delay(timeoutMillis);
1158 +                        done = true;
1159 +                    } catch (InterruptedException ok) {}
1160 +                }
1161 +            };
1162 +    }
1163 +
1164      public static class TrackedShortRunnable implements Runnable {
1165          public volatile boolean done = false;
1166          public void run() {
1167              try {
1168 <                Thread.sleep(SMALL_DELAY_MS);
1168 >                delay(SHORT_DELAY_MS);
1169 >                done = true;
1170 >            } catch (InterruptedException ok) {}
1171 >        }
1172 >    }
1173 >
1174 >    public static class TrackedSmallRunnable implements Runnable {
1175 >        public volatile boolean done = false;
1176 >        public void run() {
1177 >            try {
1178 >                delay(SMALL_DELAY_MS);
1179                  done = true;
1180              } catch (InterruptedException ok) {}
1181          }
# Line 774 | Line 1185 | public class JSR166TestCase extends Test
1185          public volatile boolean done = false;
1186          public void run() {
1187              try {
1188 <                Thread.sleep(MEDIUM_DELAY_MS);
1188 >                delay(MEDIUM_DELAY_MS);
1189                  done = true;
1190              } catch (InterruptedException ok) {}
1191          }
# Line 784 | Line 1195 | public class JSR166TestCase extends Test
1195          public volatile boolean done = false;
1196          public void run() {
1197              try {
1198 <                Thread.sleep(LONG_DELAY_MS);
1198 >                delay(LONG_DELAY_MS);
1199                  done = true;
1200              } catch (InterruptedException ok) {}
1201          }
# Line 801 | Line 1212 | public class JSR166TestCase extends Test
1212          public volatile boolean done = false;
1213          public Object call() {
1214              try {
1215 <                Thread.sleep(SMALL_DELAY_MS);
1215 >                delay(SMALL_DELAY_MS);
1216                  done = true;
1217              } catch (InterruptedException ok) {}
1218              return Boolean.TRUE;
# Line 847 | Line 1258 | public class JSR166TestCase extends Test
1258                                        ThreadPoolExecutor executor) {}
1259      }
1260  
1261 +    /**
1262 +     * A CyclicBarrier that uses timed await and fails with
1263 +     * AssertionFailedErrors instead of throwing checked exceptions.
1264 +     */
1265 +    public class CheckedBarrier extends CyclicBarrier {
1266 +        public CheckedBarrier(int parties) { super(parties); }
1267 +
1268 +        public int await() {
1269 +            try {
1270 +                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1271 +            } catch (TimeoutException e) {
1272 +                throw new AssertionFailedError("timed out");
1273 +            } catch (Exception e) {
1274 +                AssertionFailedError afe =
1275 +                    new AssertionFailedError("Unexpected exception: " + e);
1276 +                afe.initCause(e);
1277 +                throw afe;
1278 +            }
1279 +        }
1280 +    }
1281 +
1282 +    void checkEmpty(BlockingQueue q) {
1283 +        try {
1284 +            assertTrue(q.isEmpty());
1285 +            assertEquals(0, q.size());
1286 +            assertNull(q.peek());
1287 +            assertNull(q.poll());
1288 +            assertNull(q.poll(0, MILLISECONDS));
1289 +            assertEquals(q.toString(), "[]");
1290 +            assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1291 +            assertFalse(q.iterator().hasNext());
1292 +            try {
1293 +                q.element();
1294 +                shouldThrow();
1295 +            } catch (NoSuchElementException success) {}
1296 +            try {
1297 +                q.iterator().next();
1298 +                shouldThrow();
1299 +            } catch (NoSuchElementException success) {}
1300 +            try {
1301 +                q.remove();
1302 +                shouldThrow();
1303 +            } catch (NoSuchElementException success) {}
1304 +        } catch (InterruptedException ie) {
1305 +            threadUnexpectedException(ie);
1306 +        }
1307 +    }
1308 +
1309 +    void assertSerialEquals(Object x, Object y) {
1310 +        assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1311 +    }
1312 +
1313 +    void assertNotSerialEquals(Object x, Object y) {
1314 +        assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1315 +    }
1316 +
1317 +    byte[] serialBytes(Object o) {
1318 +        try {
1319 +            ByteArrayOutputStream bos = new ByteArrayOutputStream();
1320 +            ObjectOutputStream oos = new ObjectOutputStream(bos);
1321 +            oos.writeObject(o);
1322 +            oos.flush();
1323 +            oos.close();
1324 +            return bos.toByteArray();
1325 +        } catch (Throwable t) {
1326 +            threadUnexpectedException(t);
1327 +            return new byte[0];
1328 +        }
1329 +    }
1330 +
1331 +    @SuppressWarnings("unchecked")
1332 +    <T> T serialClone(T o) {
1333 +        try {
1334 +            ObjectInputStream ois = new ObjectInputStream
1335 +                (new ByteArrayInputStream(serialBytes(o)));
1336 +            T clone = (T) ois.readObject();
1337 +            assertSame(o.getClass(), clone.getClass());
1338 +            return clone;
1339 +        } catch (Throwable t) {
1340 +            threadUnexpectedException(t);
1341 +            return null;
1342 +        }
1343 +    }
1344   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines