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.55 by jsr166, Mon Sep 20 20:42:37 2010 UTC vs.
Revision 1.136 by jsr166, Fri Sep 4 18:16:28 2015 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.PropertyPermission;
11 import java.util.concurrent.*;
12 import java.util.concurrent.atomic.AtomicReference;
9   import static java.util.concurrent.TimeUnit.MILLISECONDS;
10 + import static java.util.concurrent.TimeUnit.NANOSECONDS;
11 +
12 + import java.io.ByteArrayInputStream;
13 + import java.io.ByteArrayOutputStream;
14 + import java.io.ObjectInputStream;
15 + import java.io.ObjectOutputStream;
16 + import java.lang.management.ManagementFactory;
17 + import java.lang.management.ThreadInfo;
18 + import java.lang.reflect.Constructor;
19 + import java.lang.reflect.Method;
20 + import java.lang.reflect.Modifier;
21   import java.security.CodeSource;
22   import java.security.Permission;
23   import java.security.PermissionCollection;
# Line 18 | Line 25 | import java.security.Permissions;
25   import java.security.Policy;
26   import java.security.ProtectionDomain;
27   import java.security.SecurityPermission;
28 + import java.util.ArrayList;
29 + import java.util.Arrays;
30 + import java.util.Date;
31 + import java.util.Enumeration;
32 + import java.util.Iterator;
33 + import java.util.List;
34 + import java.util.NoSuchElementException;
35 + import java.util.PropertyPermission;
36 + import java.util.concurrent.BlockingQueue;
37 + import java.util.concurrent.Callable;
38 + import java.util.concurrent.CountDownLatch;
39 + import java.util.concurrent.CyclicBarrier;
40 + import java.util.concurrent.ExecutorService;
41 + import java.util.concurrent.Future;
42 + import java.util.concurrent.RecursiveAction;
43 + import java.util.concurrent.RecursiveTask;
44 + import java.util.concurrent.RejectedExecutionHandler;
45 + import java.util.concurrent.Semaphore;
46 + import java.util.concurrent.ThreadFactory;
47 + import java.util.concurrent.ThreadPoolExecutor;
48 + import java.util.concurrent.TimeoutException;
49 + import java.util.concurrent.atomic.AtomicReference;
50 + import java.util.regex.Pattern;
51 +
52 + import junit.framework.AssertionFailedError;
53 + import junit.framework.Test;
54 + import junit.framework.TestCase;
55 + import junit.framework.TestResult;
56 + import junit.framework.TestSuite;
57  
58   /**
59   * Base class for JSR166 Junit TCK tests.  Defines some constants,
# Line 60 | Line 96 | import java.security.SecurityPermission;
96   *
97   * </ol>
98   *
99 < * <p> <b>Other notes</b>
99 > * <p><b>Other notes</b>
100   * <ul>
101   *
102   * <li> Usually, there is one testcase method per JSR166 method
# Line 96 | Line 132 | public class JSR166TestCase extends Test
132      private static final boolean useSecurityManager =
133          Boolean.getBoolean("jsr166.useSecurityManager");
134  
135 +    protected static final boolean expensiveTests =
136 +        Boolean.getBoolean("jsr166.expensiveTests");
137 +
138 +    /**
139 +     * If true, also run tests that are not part of the official tck
140 +     * because they test unspecified implementation details.
141 +     */
142 +    protected static final boolean testImplementationDetails =
143 +        Boolean.getBoolean("jsr166.testImplementationDetails");
144 +
145 +    /**
146 +     * If true, report on stdout all "slow" tests, that is, ones that
147 +     * take more than profileThreshold milliseconds to execute.
148 +     */
149 +    private static final boolean profileTests =
150 +        Boolean.getBoolean("jsr166.profileTests");
151 +
152 +    /**
153 +     * The number of milliseconds that tests are permitted for
154 +     * execution without being reported, when profileTests is set.
155 +     */
156 +    private static final long profileThreshold =
157 +        Long.getLong("jsr166.profileThreshold", 100);
158 +
159 +    /**
160 +     * The number of repetitions per test (for tickling rare bugs).
161 +     */
162 +    private static final int runsPerTest =
163 +        Integer.getInteger("jsr166.runsPerTest", 1);
164 +
165 +    /**
166 +     * The number of repetitions of the test suite (for finding leaks?).
167 +     */
168 +    private static final int suiteRuns =
169 +        Integer.getInteger("jsr166.suiteRuns", 1);
170 +
171 +    public JSR166TestCase() { super(); }
172 +    public JSR166TestCase(String name) { super(name); }
173 +
174 +    /**
175 +     * A filter for tests to run, matching strings of the form
176 +     * methodName(className), e.g. "testInvokeAll5(ForkJoinPoolTest)"
177 +     * Usefully combined with jsr166.runsPerTest.
178 +     */
179 +    private static final Pattern methodFilter = methodFilter();
180 +
181 +    private static Pattern methodFilter() {
182 +        String regex = System.getProperty("jsr166.methodFilter");
183 +        return (regex == null) ? null : Pattern.compile(regex);
184 +    }
185 +
186 +    protected void runTest() throws Throwable {
187 +        if (methodFilter == null
188 +            || methodFilter.matcher(toString()).find()) {
189 +            for (int i = 0; i < runsPerTest; i++) {
190 +                if (profileTests)
191 +                    runTestProfiled();
192 +                else
193 +                    super.runTest();
194 +            }
195 +        }
196 +    }
197 +
198 +    protected void runTestProfiled() throws Throwable {
199 +        // Warmup run, notably to trigger all needed classloading.
200 +        super.runTest();
201 +        long t0 = System.nanoTime();
202 +        try {
203 +            super.runTest();
204 +        } finally {
205 +            long elapsedMillis = millisElapsedSince(t0);
206 +            if (elapsedMillis >= profileThreshold)
207 +                System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
208 +        }
209 +    }
210 +
211      /**
212 <     * Runs all JSR166 unit tests using junit.textui.TestRunner
212 >     * Runs all JSR166 unit tests using junit.textui.TestRunner.
213       */
214      public static void main(String[] args) {
215 +        main(suite(), args);
216 +    }
217 +
218 +    /**
219 +     * Runs all unit tests in the given test suite.
220 +     * Actual behavior influenced by jsr166.* system properties.
221 +     */
222 +    static void main(Test suite, String[] args) {
223          if (useSecurityManager) {
224              System.err.println("Setting a permissive security manager");
225              Policy.setPolicy(permissivePolicy());
226              System.setSecurityManager(new SecurityManager());
227          }
228 <        int iters = 1;
229 <        if (args.length > 0)
230 <            iters = Integer.parseInt(args[0]);
231 <        Test s = suite();
112 <        for (int i = 0; i < iters; ++i) {
113 <            junit.textui.TestRunner.run(s);
228 >        for (int i = 0; i < suiteRuns; i++) {
229 >            TestResult result = junit.textui.TestRunner.run(suite);
230 >            if (!result.wasSuccessful())
231 >                System.exit(1);
232              System.gc();
233              System.runFinalization();
234          }
235 <        System.exit(0);
235 >    }
236 >
237 >    public static TestSuite newTestSuite(Object... suiteOrClasses) {
238 >        TestSuite suite = new TestSuite();
239 >        for (Object suiteOrClass : suiteOrClasses) {
240 >            if (suiteOrClass instanceof TestSuite)
241 >                suite.addTest((TestSuite) suiteOrClass);
242 >            else if (suiteOrClass instanceof Class)
243 >                suite.addTest(new TestSuite((Class<?>) suiteOrClass));
244 >            else
245 >                throw new ClassCastException("not a test suite or class");
246 >        }
247 >        return suite;
248 >    }
249 >
250 >    public static void addNamedTestClasses(TestSuite suite,
251 >                                           String... testClassNames) {
252 >        for (String testClassName : testClassNames) {
253 >            try {
254 >                Class<?> testClass = Class.forName(testClassName);
255 >                Method m = testClass.getDeclaredMethod("suite",
256 >                                                       new Class<?>[0]);
257 >                suite.addTest(newTestSuite((Test)m.invoke(null)));
258 >            } catch (Exception e) {
259 >                throw new Error("Missing test class", e);
260 >            }
261 >        }
262 >    }
263 >
264 >    public static final double JAVA_CLASS_VERSION;
265 >    public static final String JAVA_SPECIFICATION_VERSION;
266 >    static {
267 >        try {
268 >            JAVA_CLASS_VERSION = java.security.AccessController.doPrivileged(
269 >                new java.security.PrivilegedAction<Double>() {
270 >                public Double run() {
271 >                    return Double.valueOf(System.getProperty("java.class.version"));}});
272 >            JAVA_SPECIFICATION_VERSION = java.security.AccessController.doPrivileged(
273 >                new java.security.PrivilegedAction<String>() {
274 >                public String run() {
275 >                    return System.getProperty("java.specification.version");}});
276 >        } catch (Throwable t) {
277 >            throw new Error(t);
278 >        }
279 >    }
280 >
281 >    public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
282 >    public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
283 >    public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
284 >    public static boolean atLeastJava9() {
285 >        // As of 2015-09, java9 still uses 52.0 class file version
286 >        return JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?(9|[0-9][0-9])$");
287 >    }
288 >    // public static boolean atLeastJava9() { return JAVA_CLASS_VERSION >= 53.0; }
289 >    public static boolean atLeastJava10() {
290 >        return JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?[0-9][0-9]$");
291      }
292  
293      /**
294 <     * Collects all JSR166 unit tests as one suite
294 >     * Collects all JSR166 unit tests as one suite.
295       */
296      public static Test suite() {
297 <        TestSuite suite = new TestSuite("JSR166 Unit Tests");
298 <
299 <        suite.addTest(new TestSuite(ForkJoinPoolTest.class));
300 <        suite.addTest(new TestSuite(ForkJoinTaskTest.class));
301 <        suite.addTest(new TestSuite(RecursiveActionTest.class));
302 <        suite.addTest(new TestSuite(RecursiveTaskTest.class));
303 <        suite.addTest(new TestSuite(LinkedTransferQueueTest.class));
304 <        suite.addTest(new TestSuite(PhaserTest.class));
305 <        suite.addTest(new TestSuite(ThreadLocalRandomTest.class));
306 <        suite.addTest(new TestSuite(AbstractExecutorServiceTest.class));
307 <        suite.addTest(new TestSuite(AbstractQueueTest.class));
308 <        suite.addTest(new TestSuite(AbstractQueuedSynchronizerTest.class));
309 <        suite.addTest(new TestSuite(AbstractQueuedLongSynchronizerTest.class));
310 <        suite.addTest(new TestSuite(ArrayBlockingQueueTest.class));
311 <        suite.addTest(new TestSuite(ArrayDequeTest.class));
312 <        suite.addTest(new TestSuite(AtomicBooleanTest.class));
313 <        suite.addTest(new TestSuite(AtomicIntegerArrayTest.class));
314 <        suite.addTest(new TestSuite(AtomicIntegerFieldUpdaterTest.class));
315 <        suite.addTest(new TestSuite(AtomicIntegerTest.class));
316 <        suite.addTest(new TestSuite(AtomicLongArrayTest.class));
317 <        suite.addTest(new TestSuite(AtomicLongFieldUpdaterTest.class));
318 <        suite.addTest(new TestSuite(AtomicLongTest.class));
319 <        suite.addTest(new TestSuite(AtomicMarkableReferenceTest.class));
320 <        suite.addTest(new TestSuite(AtomicReferenceArrayTest.class));
321 <        suite.addTest(new TestSuite(AtomicReferenceFieldUpdaterTest.class));
322 <        suite.addTest(new TestSuite(AtomicReferenceTest.class));
323 <        suite.addTest(new TestSuite(AtomicStampedReferenceTest.class));
324 <        suite.addTest(new TestSuite(ConcurrentHashMapTest.class));
325 <        suite.addTest(new TestSuite(ConcurrentLinkedDequeTest.class));
326 <        suite.addTest(new TestSuite(ConcurrentLinkedQueueTest.class));
327 <        suite.addTest(new TestSuite(ConcurrentSkipListMapTest.class));
328 <        suite.addTest(new TestSuite(ConcurrentSkipListSubMapTest.class));
329 <        suite.addTest(new TestSuite(ConcurrentSkipListSetTest.class));
330 <        suite.addTest(new TestSuite(ConcurrentSkipListSubSetTest.class));
331 <        suite.addTest(new TestSuite(CopyOnWriteArrayListTest.class));
332 <        suite.addTest(new TestSuite(CopyOnWriteArraySetTest.class));
333 <        suite.addTest(new TestSuite(CountDownLatchTest.class));
334 <        suite.addTest(new TestSuite(CyclicBarrierTest.class));
335 <        suite.addTest(new TestSuite(DelayQueueTest.class));
336 <        suite.addTest(new TestSuite(EntryTest.class));
337 <        suite.addTest(new TestSuite(ExchangerTest.class));
338 <        suite.addTest(new TestSuite(ExecutorsTest.class));
339 <        suite.addTest(new TestSuite(ExecutorCompletionServiceTest.class));
340 <        suite.addTest(new TestSuite(FutureTaskTest.class));
341 <        suite.addTest(new TestSuite(LinkedBlockingDequeTest.class));
342 <        suite.addTest(new TestSuite(LinkedBlockingQueueTest.class));
343 <        suite.addTest(new TestSuite(LinkedListTest.class));
344 <        suite.addTest(new TestSuite(LockSupportTest.class));
345 <        suite.addTest(new TestSuite(PriorityBlockingQueueTest.class));
346 <        suite.addTest(new TestSuite(PriorityQueueTest.class));
347 <        suite.addTest(new TestSuite(ReentrantLockTest.class));
348 <        suite.addTest(new TestSuite(ReentrantReadWriteLockTest.class));
349 <        suite.addTest(new TestSuite(ScheduledExecutorTest.class));
350 <        suite.addTest(new TestSuite(ScheduledExecutorSubclassTest.class));
351 <        suite.addTest(new TestSuite(SemaphoreTest.class));
352 <        suite.addTest(new TestSuite(SynchronousQueueTest.class));
353 <        suite.addTest(new TestSuite(SystemTest.class));
354 <        suite.addTest(new TestSuite(ThreadLocalTest.class));
355 <        suite.addTest(new TestSuite(ThreadPoolExecutorTest.class));
356 <        suite.addTest(new TestSuite(ThreadPoolExecutorSubclassTest.class));
357 <        suite.addTest(new TestSuite(ThreadTest.class));
358 <        suite.addTest(new TestSuite(TimeUnitTest.class));
359 <        suite.addTest(new TestSuite(TreeMapTest.class));
360 <        suite.addTest(new TestSuite(TreeSetTest.class));
361 <        suite.addTest(new TestSuite(TreeSubMapTest.class));
362 <        suite.addTest(new TestSuite(TreeSubSetTest.class));
297 >        // Java7+ test classes
298 >        TestSuite suite = newTestSuite(
299 >            ForkJoinPoolTest.suite(),
300 >            ForkJoinTaskTest.suite(),
301 >            RecursiveActionTest.suite(),
302 >            RecursiveTaskTest.suite(),
303 >            LinkedTransferQueueTest.suite(),
304 >            PhaserTest.suite(),
305 >            ThreadLocalRandomTest.suite(),
306 >            AbstractExecutorServiceTest.suite(),
307 >            AbstractQueueTest.suite(),
308 >            AbstractQueuedSynchronizerTest.suite(),
309 >            AbstractQueuedLongSynchronizerTest.suite(),
310 >            ArrayBlockingQueueTest.suite(),
311 >            ArrayDequeTest.suite(),
312 >            AtomicBooleanTest.suite(),
313 >            AtomicIntegerArrayTest.suite(),
314 >            AtomicIntegerFieldUpdaterTest.suite(),
315 >            AtomicIntegerTest.suite(),
316 >            AtomicLongArrayTest.suite(),
317 >            AtomicLongFieldUpdaterTest.suite(),
318 >            AtomicLongTest.suite(),
319 >            AtomicMarkableReferenceTest.suite(),
320 >            AtomicReferenceArrayTest.suite(),
321 >            AtomicReferenceFieldUpdaterTest.suite(),
322 >            AtomicReferenceTest.suite(),
323 >            AtomicStampedReferenceTest.suite(),
324 >            ConcurrentHashMapTest.suite(),
325 >            ConcurrentLinkedDequeTest.suite(),
326 >            ConcurrentLinkedQueueTest.suite(),
327 >            ConcurrentSkipListMapTest.suite(),
328 >            ConcurrentSkipListSubMapTest.suite(),
329 >            ConcurrentSkipListSetTest.suite(),
330 >            ConcurrentSkipListSubSetTest.suite(),
331 >            CopyOnWriteArrayListTest.suite(),
332 >            CopyOnWriteArraySetTest.suite(),
333 >            CountDownLatchTest.suite(),
334 >            CyclicBarrierTest.suite(),
335 >            DelayQueueTest.suite(),
336 >            EntryTest.suite(),
337 >            ExchangerTest.suite(),
338 >            ExecutorsTest.suite(),
339 >            ExecutorCompletionServiceTest.suite(),
340 >            FutureTaskTest.suite(),
341 >            LinkedBlockingDequeTest.suite(),
342 >            LinkedBlockingQueueTest.suite(),
343 >            LinkedListTest.suite(),
344 >            LockSupportTest.suite(),
345 >            PriorityBlockingQueueTest.suite(),
346 >            PriorityQueueTest.suite(),
347 >            ReentrantLockTest.suite(),
348 >            ReentrantReadWriteLockTest.suite(),
349 >            ScheduledExecutorTest.suite(),
350 >            ScheduledExecutorSubclassTest.suite(),
351 >            SemaphoreTest.suite(),
352 >            SynchronousQueueTest.suite(),
353 >            SystemTest.suite(),
354 >            ThreadLocalTest.suite(),
355 >            ThreadPoolExecutorTest.suite(),
356 >            ThreadPoolExecutorSubclassTest.suite(),
357 >            ThreadTest.suite(),
358 >            TimeUnitTest.suite(),
359 >            TreeMapTest.suite(),
360 >            TreeSetTest.suite(),
361 >            TreeSubMapTest.suite(),
362 >            TreeSubSetTest.suite());
363 >
364 >        // Java8+ test classes
365 >        if (atLeastJava8()) {
366 >            String[] java8TestClassNames = {
367 >                "Atomic8Test",
368 >                "CompletableFutureTest",
369 >                "ConcurrentHashMap8Test",
370 >                "CountedCompleterTest",
371 >                "DoubleAccumulatorTest",
372 >                "DoubleAdderTest",
373 >                "ForkJoinPool8Test",
374 >                "ForkJoinTask8Test",
375 >                "LongAccumulatorTest",
376 >                "LongAdderTest",
377 >                "SplittableRandomTest",
378 >                "StampedLockTest",
379 >                "ThreadLocalRandom8Test",
380 >            };
381 >            addNamedTestClasses(suite, java8TestClassNames);
382 >        }
383 >
384 >        // Java9+ test classes
385 >        if (atLeastJava9()) {
386 >            String[] java9TestClassNames = {
387 >                "ThreadPoolExecutor9Test",
388 >            };
389 >            addNamedTestClasses(suite, java9TestClassNames);
390 >        }
391  
392          return suite;
393      }
394  
395 +    /** Returns list of junit-style test method names in given class. */
396 +    public static ArrayList<String> testMethodNames(Class<?> testClass) {
397 +        Method[] methods = testClass.getDeclaredMethods();
398 +        ArrayList<String> names = new ArrayList<String>(methods.length);
399 +        for (Method method : methods) {
400 +            if (method.getName().startsWith("test")
401 +                && Modifier.isPublic(method.getModifiers())
402 +                // method.getParameterCount() requires jdk8+
403 +                && method.getParameterTypes().length == 0) {
404 +                names.add(method.getName());
405 +            }
406 +        }
407 +        return names;
408 +    }
409 +
410 +    /**
411 +     * Returns junit-style testSuite for the given test class, but
412 +     * parameterized by passing extra data to each test.
413 +     */
414 +    public static <ExtraData> Test parameterizedTestSuite
415 +        (Class<? extends JSR166TestCase> testClass,
416 +         Class<ExtraData> dataClass,
417 +         ExtraData data) {
418 +        try {
419 +            TestSuite suite = new TestSuite();
420 +            Constructor c =
421 +                testClass.getDeclaredConstructor(dataClass, String.class);
422 +            for (String methodName : testMethodNames(testClass))
423 +                suite.addTest((Test) c.newInstance(data, methodName));
424 +            return suite;
425 +        } catch (Exception e) {
426 +            throw new Error(e);
427 +        }
428 +    }
429 +
430 +    /**
431 +     * Returns junit-style testSuite for the jdk8 extension of the
432 +     * given test class, but parameterized by passing extra data to
433 +     * each test.  Uses reflection to allow compilation in jdk7.
434 +     */
435 +    public static <ExtraData> Test jdk8ParameterizedTestSuite
436 +        (Class<? extends JSR166TestCase> testClass,
437 +         Class<ExtraData> dataClass,
438 +         ExtraData data) {
439 +        if (atLeastJava8()) {
440 +            String name = testClass.getName();
441 +            String name8 = name.replaceAll("Test$", "8Test");
442 +            if (name.equals(name8)) throw new Error(name);
443 +            try {
444 +                return (Test)
445 +                    Class.forName(name8)
446 +                    .getMethod("testSuite", new Class[] { dataClass })
447 +                    .invoke(null, data);
448 +            } catch (Exception e) {
449 +                throw new Error(e);
450 +            }
451 +        } else {
452 +            return new TestSuite();
453 +        }
454 +
455 +    }
456 +
457 +    // Delays for timing-dependent tests, in milliseconds.
458  
459      public static long SHORT_DELAY_MS;
460      public static long SMALL_DELAY_MS;
461      public static long MEDIUM_DELAY_MS;
462      public static long LONG_DELAY_MS;
463  
200
464      /**
465       * Returns the shortest timed delay. This could
466       * be reimplemented to use for example a Property.
# Line 206 | Line 469 | public class JSR166TestCase extends Test
469          return 50;
470      }
471  
209
472      /**
473       * Sets delays as multiples of SHORT_DELAY.
474       */
# Line 214 | Line 476 | public class JSR166TestCase extends Test
476          SHORT_DELAY_MS = getShortDelay();
477          SMALL_DELAY_MS  = SHORT_DELAY_MS * 5;
478          MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
479 <        LONG_DELAY_MS   = SHORT_DELAY_MS * 50;
479 >        LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
480 >    }
481 >
482 >    /**
483 >     * Returns a timeout in milliseconds to be used in tests that
484 >     * verify that operations block or time out.
485 >     */
486 >    long timeoutMillis() {
487 >        return SHORT_DELAY_MS / 4;
488 >    }
489 >
490 >    /**
491 >     * Returns a new Date instance representing a time at least
492 >     * delayMillis milliseconds in the future.
493 >     */
494 >    Date delayedDate(long delayMillis) {
495 >        // Add 1 because currentTimeMillis is known to round into the past.
496 >        return new Date(System.currentTimeMillis() + delayMillis + 1);
497      }
498  
499      /**
# Line 238 | Line 517 | public class JSR166TestCase extends Test
517      }
518  
519      /**
520 +     * Extra checks that get done for all test cases.
521 +     *
522       * Triggers test case failure if any thread assertions have failed,
523       * by rethrowing, in the test harness thread, any exception recorded
524       * earlier by threadRecordFailure.
525 +     *
526 +     * Triggers test case failure if interrupt status is set in the main thread.
527       */
528      public void tearDown() throws Exception {
529 <        Throwable t = threadFailure.get();
529 >        Throwable t = threadFailure.getAndSet(null);
530          if (t != null) {
531              if (t instanceof Error)
532                  throw (Error) t;
# Line 251 | Line 534 | public class JSR166TestCase extends Test
534                  throw (RuntimeException) t;
535              else if (t instanceof Exception)
536                  throw (Exception) t;
537 <            else
538 <                throw new AssertionError(t);
537 >            else {
538 >                AssertionFailedError afe =
539 >                    new AssertionFailedError(t.toString());
540 >                afe.initCause(t);
541 >                throw afe;
542 >            }
543 >        }
544 >
545 >        if (Thread.interrupted())
546 >            throw new AssertionFailedError("interrupt status set in main thread");
547 >
548 >        checkForkJoinPoolThreadLeaks();
549 >    }
550 >
551 >    /**
552 >     * Finds missing try { ... } finally { joinPool(e); }
553 >     */
554 >    void checkForkJoinPoolThreadLeaks() throws InterruptedException {
555 >        Thread[] survivors = new Thread[5];
556 >        int count = Thread.enumerate(survivors);
557 >        for (int i = 0; i < count; i++) {
558 >            Thread thread = survivors[i];
559 >            String name = thread.getName();
560 >            if (name.startsWith("ForkJoinPool-")) {
561 >                // give thread some time to terminate
562 >                thread.join(LONG_DELAY_MS);
563 >                if (!thread.isAlive()) continue;
564 >                throw new AssertionFailedError
565 >                    (String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n",
566 >                                   toString(), name));
567 >            }
568          }
569      }
570  
571      /**
572       * Just like fail(reason), but additionally recording (using
573 <     * threadRecordFailure) any AssertionError thrown, so that the current
574 <     * testcase will fail.
573 >     * threadRecordFailure) any AssertionFailedError thrown, so that
574 >     * the current testcase will fail.
575       */
576      public void threadFail(String reason) {
577          try {
578              fail(reason);
579 <        } catch (Throwable t) {
579 >        } catch (AssertionFailedError t) {
580              threadRecordFailure(t);
581              fail(reason);
582          }
# Line 272 | Line 584 | public class JSR166TestCase extends Test
584  
585      /**
586       * Just like assertTrue(b), but additionally recording (using
587 <     * threadRecordFailure) any AssertionError thrown, so that the current
588 <     * testcase will fail.
587 >     * threadRecordFailure) any AssertionFailedError thrown, so that
588 >     * the current testcase will fail.
589       */
590      public void threadAssertTrue(boolean b) {
591          try {
592              assertTrue(b);
593 <        } catch (AssertionError t) {
593 >        } catch (AssertionFailedError t) {
594              threadRecordFailure(t);
595              throw t;
596          }
# Line 286 | Line 598 | public class JSR166TestCase extends Test
598  
599      /**
600       * Just like assertFalse(b), but additionally recording (using
601 <     * threadRecordFailure) any AssertionError thrown, so that the
602 <     * current testcase will fail.
601 >     * threadRecordFailure) any AssertionFailedError thrown, so that
602 >     * the current testcase will fail.
603       */
604      public void threadAssertFalse(boolean b) {
605          try {
606              assertFalse(b);
607 <        } catch (AssertionError t) {
607 >        } catch (AssertionFailedError t) {
608              threadRecordFailure(t);
609              throw t;
610          }
# Line 300 | Line 612 | public class JSR166TestCase extends Test
612  
613      /**
614       * Just like assertNull(x), but additionally recording (using
615 <     * threadRecordFailure) any AssertionError thrown, so that the
616 <     * current testcase will fail.
615 >     * threadRecordFailure) any AssertionFailedError thrown, so that
616 >     * the current testcase will fail.
617       */
618      public void threadAssertNull(Object x) {
619          try {
620              assertNull(x);
621 <        } catch (AssertionError t) {
621 >        } catch (AssertionFailedError t) {
622              threadRecordFailure(t);
623              throw t;
624          }
# Line 314 | Line 626 | public class JSR166TestCase extends Test
626  
627      /**
628       * Just like assertEquals(x, y), but additionally recording (using
629 <     * threadRecordFailure) any AssertionError thrown, so that the
630 <     * current testcase will fail.
629 >     * threadRecordFailure) any AssertionFailedError thrown, so that
630 >     * the current testcase will fail.
631       */
632      public void threadAssertEquals(long x, long y) {
633          try {
634              assertEquals(x, y);
635 <        } catch (AssertionError t) {
635 >        } catch (AssertionFailedError t) {
636              threadRecordFailure(t);
637              throw t;
638          }
# Line 328 | Line 640 | public class JSR166TestCase extends Test
640  
641      /**
642       * Just like assertEquals(x, y), but additionally recording (using
643 <     * threadRecordFailure) any AssertionError thrown, so that the
644 <     * current testcase will fail.
643 >     * threadRecordFailure) any AssertionFailedError thrown, so that
644 >     * the current testcase will fail.
645       */
646      public void threadAssertEquals(Object x, Object y) {
647          try {
648              assertEquals(x, y);
649 <        } catch (AssertionError t) {
650 <            threadRecordFailure(t);
651 <            throw t;
649 >        } catch (AssertionFailedError fail) {
650 >            threadRecordFailure(fail);
651 >            throw fail;
652 >        } catch (Throwable fail) {
653 >            threadUnexpectedException(fail);
654          }
655      }
656  
657      /**
658       * Just like assertSame(x, y), but additionally recording (using
659 <     * threadRecordFailure) any AssertionError thrown, so that the
660 <     * current testcase will fail.
659 >     * threadRecordFailure) any AssertionFailedError thrown, so that
660 >     * the current testcase will fail.
661       */
662      public void threadAssertSame(Object x, Object y) {
663          try {
664              assertSame(x, y);
665 <        } catch (AssertionError t) {
666 <            threadRecordFailure(t);
667 <            throw t;
665 >        } catch (AssertionFailedError fail) {
666 >            threadRecordFailure(fail);
667 >            throw fail;
668          }
669      }
670  
# Line 369 | Line 683 | public class JSR166TestCase extends Test
683      }
684  
685      /**
686 <     * Calls threadFail with message "Unexpected exception" + ex.
686 >     * Records the given exception using {@link #threadRecordFailure},
687 >     * then rethrows the exception, wrapping it in an
688 >     * AssertionFailedError if necessary.
689       */
690      public void threadUnexpectedException(Throwable t) {
691          threadRecordFailure(t);
692          t.printStackTrace();
377        // Rethrow, wrapping in an AssertionError if necessary
693          if (t instanceof RuntimeException)
694              throw (RuntimeException) t;
695          else if (t instanceof Error)
696              throw (Error) t;
697          else {
698 <            AssertionError ae = new AssertionError("unexpected exception: " + t);
699 <            t.initCause(t);
700 <            throw ae;
698 >            AssertionFailedError afe =
699 >                new AssertionFailedError("unexpected exception: " + t);
700 >            afe.initCause(t);
701 >            throw afe;
702 >        }
703 >    }
704 >
705 >    /**
706 >     * Delays, via Thread.sleep, for the given millisecond delay, but
707 >     * if the sleep is shorter than specified, may re-sleep or yield
708 >     * until time elapses.
709 >     */
710 >    static void delay(long millis) throws InterruptedException {
711 >        long startTime = System.nanoTime();
712 >        long ns = millis * 1000 * 1000;
713 >        for (;;) {
714 >            if (millis > 0L)
715 >                Thread.sleep(millis);
716 >            else // too short to sleep
717 >                Thread.yield();
718 >            long d = ns - (System.nanoTime() - startTime);
719 >            if (d > 0L)
720 >                millis = d / (1000 * 1000);
721 >            else
722 >                break;
723          }
724      }
725  
726      /**
727       * Waits out termination of a thread pool or fails doing so.
728       */
729 <    public void joinPool(ExecutorService exec) {
729 >    void joinPool(ExecutorService exec) {
730          try {
731              exec.shutdown();
732 <            assertTrue("ExecutorService did not terminate in a timely manner",
733 <                       exec.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
732 >            if (!exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS))
733 >                fail("ExecutorService " + exec +
734 >                     " did not terminate in a timely manner");
735          } catch (SecurityException ok) {
736              // Allowed in case test doesn't have privs
737 <        } catch (InterruptedException ie) {
737 >        } catch (InterruptedException fail) {
738 >            fail("Unexpected InterruptedException");
739 >        }
740 >    }
741 >
742 >    /**
743 >     * A debugging tool to print all stack traces, as jstack does.
744 >     */
745 >    static void printAllStackTraces() {
746 >        for (ThreadInfo info :
747 >                 ManagementFactory.getThreadMXBean()
748 >                 .dumpAllThreads(true, true))
749 >            System.err.print(info);
750 >    }
751 >
752 >    /**
753 >     * Checks that thread does not terminate within the default
754 >     * millisecond delay of {@code timeoutMillis()}.
755 >     */
756 >    void assertThreadStaysAlive(Thread thread) {
757 >        assertThreadStaysAlive(thread, timeoutMillis());
758 >    }
759 >
760 >    /**
761 >     * Checks that thread does not terminate within the given millisecond delay.
762 >     */
763 >    void assertThreadStaysAlive(Thread thread, long millis) {
764 >        try {
765 >            // No need to optimize the failing case via Thread.join.
766 >            delay(millis);
767 >            assertTrue(thread.isAlive());
768 >        } catch (InterruptedException fail) {
769 >            fail("Unexpected InterruptedException");
770 >        }
771 >    }
772 >
773 >    /**
774 >     * Checks that the threads do not terminate within the default
775 >     * millisecond delay of {@code timeoutMillis()}.
776 >     */
777 >    void assertThreadsStayAlive(Thread... threads) {
778 >        assertThreadsStayAlive(timeoutMillis(), threads);
779 >    }
780 >
781 >    /**
782 >     * Checks that the threads do not terminate within the given millisecond delay.
783 >     */
784 >    void assertThreadsStayAlive(long millis, Thread... threads) {
785 >        try {
786 >            // No need to optimize the failing case via Thread.join.
787 >            delay(millis);
788 >            for (Thread thread : threads)
789 >                assertTrue(thread.isAlive());
790 >        } catch (InterruptedException fail) {
791              fail("Unexpected InterruptedException");
792          }
793      }
794  
795 +    /**
796 +     * Checks that future.get times out, with the default timeout of
797 +     * {@code timeoutMillis()}.
798 +     */
799 +    void assertFutureTimesOut(Future future) {
800 +        assertFutureTimesOut(future, timeoutMillis());
801 +    }
802 +
803 +    /**
804 +     * Checks that future.get times out, with the given millisecond timeout.
805 +     */
806 +    void assertFutureTimesOut(Future future, long timeoutMillis) {
807 +        long startTime = System.nanoTime();
808 +        try {
809 +            future.get(timeoutMillis, MILLISECONDS);
810 +            shouldThrow();
811 +        } catch (TimeoutException success) {
812 +        } catch (Exception fail) {
813 +            threadUnexpectedException(fail);
814 +        } finally { future.cancel(true); }
815 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
816 +    }
817  
818      /**
819       * Fails with message "should throw exception".
# Line 417 | Line 830 | public class JSR166TestCase extends Test
830      }
831  
832      /**
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    /**
833       * The number of elements to place in collections, arrays, etc.
834       */
835      public static final int SIZE = 20;
# Line 450 | Line 854 | public class JSR166TestCase extends Test
854      public static final Integer m6  = new Integer(-6);
855      public static final Integer m10 = new Integer(-10);
856  
453
857      /**
858       * Runs Runnable r with a security policy that permits precisely
859       * the specified permissions.  If there is no current security
# Line 462 | Line 865 | public class JSR166TestCase extends Test
865          SecurityManager sm = System.getSecurityManager();
866          if (sm == null) {
867              r.run();
868 +        }
869 +        runWithSecurityManagerWithPermissions(r, permissions);
870 +    }
871 +
872 +    /**
873 +     * Runs Runnable r with a security policy that permits precisely
874 +     * the specified permissions.  If there is no current security
875 +     * manager, a temporary one is set for the duration of the
876 +     * Runnable.  We require that any security manager permit
877 +     * getPolicy/setPolicy.
878 +     */
879 +    public void runWithSecurityManagerWithPermissions(Runnable r,
880 +                                                      Permission... permissions) {
881 +        SecurityManager sm = System.getSecurityManager();
882 +        if (sm == null) {
883              Policy savedPolicy = Policy.getPolicy();
884              try {
885                  Policy.setPolicy(permissivePolicy());
886                  System.setSecurityManager(new SecurityManager());
887 <                runWithPermissions(r, permissions);
887 >                runWithSecurityManagerWithPermissions(r, permissions);
888              } finally {
889                  System.setSecurityManager(null);
890                  Policy.setPolicy(savedPolicy);
# Line 514 | Line 932 | public class JSR166TestCase extends Test
932              return perms.implies(p);
933          }
934          public void refresh() {}
935 +        public String toString() {
936 +            List<Permission> ps = new ArrayList<Permission>();
937 +            for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
938 +                ps.add(e.nextElement());
939 +            return "AdjustablePolicy with permissions " + ps;
940 +        }
941      }
942  
943      /**
# Line 536 | Line 960 | public class JSR166TestCase extends Test
960      }
961  
962      /**
963 <     * Sleep until the timeout has elapsed, or interrupted.
964 <     * Does <em>NOT</em> throw InterruptedException.
963 >     * Sleeps until the given time has elapsed.
964 >     * Throws AssertionFailedError if interrupted.
965 >     */
966 >    void sleep(long millis) {
967 >        try {
968 >            delay(millis);
969 >        } catch (InterruptedException fail) {
970 >            AssertionFailedError afe =
971 >                new AssertionFailedError("Unexpected InterruptedException");
972 >            afe.initCause(fail);
973 >            throw afe;
974 >        }
975 >    }
976 >
977 >    /**
978 >     * Spin-waits up to the specified number of milliseconds for the given
979 >     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
980 >     */
981 >    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
982 >        long startTime = System.nanoTime();
983 >        for (;;) {
984 >            Thread.State s = thread.getState();
985 >            if (s == Thread.State.BLOCKED ||
986 >                s == Thread.State.WAITING ||
987 >                s == Thread.State.TIMED_WAITING)
988 >                return;
989 >            else if (s == Thread.State.TERMINATED)
990 >                fail("Unexpected thread termination");
991 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
992 >                threadAssertTrue(thread.isAlive());
993 >                return;
994 >            }
995 >            Thread.yield();
996 >        }
997 >    }
998 >
999 >    /**
1000 >     * Waits up to LONG_DELAY_MS for the given thread to enter a wait
1001 >     * state: BLOCKED, WAITING, or TIMED_WAITING.
1002 >     */
1003 >    void waitForThreadToEnterWaitState(Thread thread) {
1004 >        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
1005 >    }
1006 >
1007 >    /**
1008 >     * Returns the number of milliseconds since time given by
1009 >     * startNanoTime, which must have been previously returned from a
1010 >     * call to {@link System#nanoTime()}.
1011       */
1012 <    void sleepTillInterrupted(long timeoutMillis) {
1012 >    static long millisElapsedSince(long startNanoTime) {
1013 >        return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
1014 >    }
1015 >
1016 > //     void assertTerminatesPromptly(long timeoutMillis, Runnable r) {
1017 > //         long startTime = System.nanoTime();
1018 > //         try {
1019 > //             r.run();
1020 > //         } catch (Throwable fail) { threadUnexpectedException(fail); }
1021 > //         if (millisElapsedSince(startTime) > timeoutMillis/2)
1022 > //             throw new AssertionFailedError("did not return promptly");
1023 > //     }
1024 >
1025 > //     void assertTerminatesPromptly(Runnable r) {
1026 > //         assertTerminatesPromptly(LONG_DELAY_MS/2, r);
1027 > //     }
1028 >
1029 >    /**
1030 >     * Checks that timed f.get() returns the expected value, and does not
1031 >     * wait for the timeout to elapse before returning.
1032 >     */
1033 >    <T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) {
1034 >        long startTime = System.nanoTime();
1035          try {
1036 <            Thread.sleep(timeoutMillis);
1037 <        } catch (InterruptedException wakeup) {}
1036 >            assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
1037 >        } catch (Throwable fail) { threadUnexpectedException(fail); }
1038 >        if (millisElapsedSince(startTime) > timeoutMillis/2)
1039 >            throw new AssertionFailedError("timed get did not return promptly");
1040 >    }
1041 >
1042 >    <T> void checkTimedGet(Future<T> f, T expectedValue) {
1043 >        checkTimedGet(f, expectedValue, LONG_DELAY_MS);
1044      }
1045  
1046      /**
1047 <     * Returns a new started Thread running the given runnable.
1047 >     * Returns a new started daemon Thread running the given runnable.
1048       */
1049      Thread newStartedThread(Runnable runnable) {
1050          Thread t = new Thread(runnable);
1051 +        t.setDaemon(true);
1052          t.start();
1053          return t;
1054      }
1055  
1056 +    /**
1057 +     * Waits for the specified time (in milliseconds) for the thread
1058 +     * to terminate (using {@link Thread#join(long)}), else interrupts
1059 +     * the thread (in the hope that it may terminate later) and fails.
1060 +     */
1061 +    void awaitTermination(Thread t, long timeoutMillis) {
1062 +        try {
1063 +            t.join(timeoutMillis);
1064 +        } catch (InterruptedException fail) {
1065 +            threadUnexpectedException(fail);
1066 +        } finally {
1067 +            if (t.getState() != Thread.State.TERMINATED) {
1068 +                t.interrupt();
1069 +                fail("Test timed out");
1070 +            }
1071 +        }
1072 +    }
1073 +
1074 +    /**
1075 +     * Waits for LONG_DELAY_MS milliseconds for the thread to
1076 +     * terminate (using {@link Thread#join(long)}), else interrupts
1077 +     * the thread (in the hope that it may terminate later) and fails.
1078 +     */
1079 +    void awaitTermination(Thread t) {
1080 +        awaitTermination(t, LONG_DELAY_MS);
1081 +    }
1082 +
1083      // Some convenient Runnable classes
1084  
1085      public abstract class CheckedRunnable implements Runnable {
# Line 562 | Line 1088 | public class JSR166TestCase extends Test
1088          public final void run() {
1089              try {
1090                  realRun();
1091 <            } catch (Throwable t) {
1092 <                threadUnexpectedException(t);
1091 >            } catch (Throwable fail) {
1092 >                threadUnexpectedException(fail);
1093              }
1094          }
1095      }
# Line 616 | Line 1142 | public class JSR166TestCase extends Test
1142                  realRun();
1143                  threadShouldThrow("InterruptedException");
1144              } catch (InterruptedException success) {
1145 <            } catch (Throwable t) {
1146 <                threadUnexpectedException(t);
1145 >                threadAssertFalse(Thread.interrupted());
1146 >            } catch (Throwable fail) {
1147 >                threadUnexpectedException(fail);
1148              }
1149          }
1150      }
# Line 628 | Line 1155 | public class JSR166TestCase extends Test
1155          public final T call() {
1156              try {
1157                  return realCall();
1158 <            } catch (Throwable t) {
1159 <                threadUnexpectedException(t);
1158 >            } catch (Throwable fail) {
1159 >                threadUnexpectedException(fail);
1160                  return null;
1161              }
1162          }
# Line 645 | Line 1172 | public class JSR166TestCase extends Test
1172                  threadShouldThrow("InterruptedException");
1173                  return result;
1174              } catch (InterruptedException success) {
1175 <            } catch (Throwable t) {
1176 <                threadUnexpectedException(t);
1175 >                threadAssertFalse(Thread.interrupted());
1176 >            } catch (Throwable fail) {
1177 >                threadUnexpectedException(fail);
1178              }
1179              return null;
1180          }
# Line 668 | Line 1196 | public class JSR166TestCase extends Test
1196  
1197      public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
1198          return new CheckedCallable<String>() {
1199 <            public String realCall() {
1199 >            protected String realCall() {
1200                  try {
1201                      latch.await();
1202                  } catch (InterruptedException quittingTime) {}
# Line 676 | Line 1204 | public class JSR166TestCase extends Test
1204              }};
1205      }
1206  
1207 +    public Runnable awaiter(final CountDownLatch latch) {
1208 +        return new CheckedRunnable() {
1209 +            public void realRun() throws InterruptedException {
1210 +                await(latch);
1211 +            }};
1212 +    }
1213 +
1214 +    public void await(CountDownLatch latch) {
1215 +        try {
1216 +            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1217 +        } catch (Throwable fail) {
1218 +            threadUnexpectedException(fail);
1219 +        }
1220 +    }
1221 +
1222 +    public void await(Semaphore semaphore) {
1223 +        try {
1224 +            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1225 +        } catch (Throwable fail) {
1226 +            threadUnexpectedException(fail);
1227 +        }
1228 +    }
1229 +
1230 + //     /**
1231 + //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1232 + //      */
1233 + //     public void await(AtomicBoolean flag) {
1234 + //         await(flag, LONG_DELAY_MS);
1235 + //     }
1236 +
1237 + //     /**
1238 + //      * Spin-waits up to the specified timeout until flag becomes true.
1239 + //      */
1240 + //     public void await(AtomicBoolean flag, long timeoutMillis) {
1241 + //         long startTime = System.nanoTime();
1242 + //         while (!flag.get()) {
1243 + //             if (millisElapsedSince(startTime) > timeoutMillis)
1244 + //                 throw new AssertionFailedError("timed out");
1245 + //             Thread.yield();
1246 + //         }
1247 + //     }
1248 +
1249      public static class NPETask implements Callable<String> {
1250          public String call() { throw new NullPointerException(); }
1251      }
# Line 686 | Line 1256 | public class JSR166TestCase extends Test
1256  
1257      public class ShortRunnable extends CheckedRunnable {
1258          protected void realRun() throws Throwable {
1259 <            Thread.sleep(SHORT_DELAY_MS);
1259 >            delay(SHORT_DELAY_MS);
1260          }
1261      }
1262  
1263      public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1264          protected void realRun() throws InterruptedException {
1265 <            Thread.sleep(SHORT_DELAY_MS);
1265 >            delay(SHORT_DELAY_MS);
1266          }
1267      }
1268  
1269      public class SmallRunnable extends CheckedRunnable {
1270          protected void realRun() throws Throwable {
1271 <            Thread.sleep(SMALL_DELAY_MS);
1271 >            delay(SMALL_DELAY_MS);
1272          }
1273      }
1274  
1275      public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1276          protected void realRun() {
1277              try {
1278 <                Thread.sleep(SMALL_DELAY_MS);
1278 >                delay(SMALL_DELAY_MS);
1279              } catch (InterruptedException ok) {}
1280          }
1281      }
1282  
1283      public class SmallCallable extends CheckedCallable {
1284          protected Object realCall() throws InterruptedException {
1285 <            Thread.sleep(SMALL_DELAY_MS);
1285 >            delay(SMALL_DELAY_MS);
1286              return Boolean.TRUE;
1287          }
1288      }
1289  
720    public class SmallInterruptedRunnable extends CheckedInterruptedRunnable {
721        protected void realRun() throws InterruptedException {
722            Thread.sleep(SMALL_DELAY_MS);
723        }
724    }
725
1290      public class MediumRunnable extends CheckedRunnable {
1291          protected void realRun() throws Throwable {
1292 <            Thread.sleep(MEDIUM_DELAY_MS);
1292 >            delay(MEDIUM_DELAY_MS);
1293          }
1294      }
1295  
1296      public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1297          protected void realRun() throws InterruptedException {
1298 <            Thread.sleep(MEDIUM_DELAY_MS);
1298 >            delay(MEDIUM_DELAY_MS);
1299          }
1300      }
1301  
1302 +    public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1303 +        return new CheckedRunnable() {
1304 +            protected void realRun() {
1305 +                try {
1306 +                    delay(timeoutMillis);
1307 +                } catch (InterruptedException ok) {}
1308 +            }};
1309 +    }
1310 +
1311      public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1312          protected void realRun() {
1313              try {
1314 <                Thread.sleep(MEDIUM_DELAY_MS);
1314 >                delay(MEDIUM_DELAY_MS);
1315              } catch (InterruptedException ok) {}
1316          }
1317      }
# Line 746 | Line 1319 | public class JSR166TestCase extends Test
1319      public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1320          protected void realRun() {
1321              try {
1322 <                Thread.sleep(LONG_DELAY_MS);
1322 >                delay(LONG_DELAY_MS);
1323              } catch (InterruptedException ok) {}
1324          }
1325      }
# Line 760 | Line 1333 | public class JSR166TestCase extends Test
1333          }
1334      }
1335  
1336 +    public interface TrackedRunnable extends Runnable {
1337 +        boolean isDone();
1338 +    }
1339 +
1340 +    public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
1341 +        return new TrackedRunnable() {
1342 +                private volatile boolean done = false;
1343 +                public boolean isDone() { return done; }
1344 +                public void run() {
1345 +                    try {
1346 +                        delay(timeoutMillis);
1347 +                        done = true;
1348 +                    } catch (InterruptedException ok) {}
1349 +                }
1350 +            };
1351 +    }
1352 +
1353      public static class TrackedShortRunnable implements Runnable {
1354          public volatile boolean done = false;
1355          public void run() {
1356              try {
1357 <                Thread.sleep(SMALL_DELAY_MS);
1357 >                delay(SHORT_DELAY_MS);
1358 >                done = true;
1359 >            } catch (InterruptedException ok) {}
1360 >        }
1361 >    }
1362 >
1363 >    public static class TrackedSmallRunnable implements Runnable {
1364 >        public volatile boolean done = false;
1365 >        public void run() {
1366 >            try {
1367 >                delay(SMALL_DELAY_MS);
1368                  done = true;
1369              } catch (InterruptedException ok) {}
1370          }
# Line 774 | Line 1374 | public class JSR166TestCase extends Test
1374          public volatile boolean done = false;
1375          public void run() {
1376              try {
1377 <                Thread.sleep(MEDIUM_DELAY_MS);
1377 >                delay(MEDIUM_DELAY_MS);
1378                  done = true;
1379              } catch (InterruptedException ok) {}
1380          }
# Line 784 | Line 1384 | public class JSR166TestCase extends Test
1384          public volatile boolean done = false;
1385          public void run() {
1386              try {
1387 <                Thread.sleep(LONG_DELAY_MS);
1387 >                delay(LONG_DELAY_MS);
1388                  done = true;
1389              } catch (InterruptedException ok) {}
1390          }
# Line 801 | Line 1401 | public class JSR166TestCase extends Test
1401          public volatile boolean done = false;
1402          public Object call() {
1403              try {
1404 <                Thread.sleep(SMALL_DELAY_MS);
1404 >                delay(SMALL_DELAY_MS);
1405                  done = true;
1406              } catch (InterruptedException ok) {}
1407              return Boolean.TRUE;
# Line 814 | Line 1414 | public class JSR166TestCase extends Test
1414      public abstract class CheckedRecursiveAction extends RecursiveAction {
1415          protected abstract void realCompute() throws Throwable;
1416  
1417 <        public final void compute() {
1417 >        @Override protected final void compute() {
1418              try {
1419                  realCompute();
1420 <            } catch (Throwable t) {
1421 <                threadUnexpectedException(t);
1420 >            } catch (Throwable fail) {
1421 >                threadUnexpectedException(fail);
1422              }
1423          }
1424      }
# Line 829 | Line 1429 | public class JSR166TestCase extends Test
1429      public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1430          protected abstract T realCompute() throws Throwable;
1431  
1432 <        public final T compute() {
1432 >        @Override protected final T compute() {
1433              try {
1434                  return realCompute();
1435 <            } catch (Throwable t) {
1436 <                threadUnexpectedException(t);
1435 >            } catch (Throwable fail) {
1436 >                threadUnexpectedException(fail);
1437                  return null;
1438              }
1439          }
# Line 847 | Line 1447 | public class JSR166TestCase extends Test
1447                                        ThreadPoolExecutor executor) {}
1448      }
1449  
1450 +    /**
1451 +     * A CyclicBarrier that uses timed await and fails with
1452 +     * AssertionFailedErrors instead of throwing checked exceptions.
1453 +     */
1454 +    public class CheckedBarrier extends CyclicBarrier {
1455 +        public CheckedBarrier(int parties) { super(parties); }
1456 +
1457 +        public int await() {
1458 +            try {
1459 +                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1460 +            } catch (TimeoutException timedOut) {
1461 +                throw new AssertionFailedError("timed out");
1462 +            } catch (Exception fail) {
1463 +                AssertionFailedError afe =
1464 +                    new AssertionFailedError("Unexpected exception: " + fail);
1465 +                afe.initCause(fail);
1466 +                throw afe;
1467 +            }
1468 +        }
1469 +    }
1470 +
1471 +    void checkEmpty(BlockingQueue q) {
1472 +        try {
1473 +            assertTrue(q.isEmpty());
1474 +            assertEquals(0, q.size());
1475 +            assertNull(q.peek());
1476 +            assertNull(q.poll());
1477 +            assertNull(q.poll(0, MILLISECONDS));
1478 +            assertEquals(q.toString(), "[]");
1479 +            assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1480 +            assertFalse(q.iterator().hasNext());
1481 +            try {
1482 +                q.element();
1483 +                shouldThrow();
1484 +            } catch (NoSuchElementException success) {}
1485 +            try {
1486 +                q.iterator().next();
1487 +                shouldThrow();
1488 +            } catch (NoSuchElementException success) {}
1489 +            try {
1490 +                q.remove();
1491 +                shouldThrow();
1492 +            } catch (NoSuchElementException success) {}
1493 +        } catch (InterruptedException fail) { threadUnexpectedException(fail); }
1494 +    }
1495 +
1496 +    void assertSerialEquals(Object x, Object y) {
1497 +        assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1498 +    }
1499 +
1500 +    void assertNotSerialEquals(Object x, Object y) {
1501 +        assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1502 +    }
1503 +
1504 +    byte[] serialBytes(Object o) {
1505 +        try {
1506 +            ByteArrayOutputStream bos = new ByteArrayOutputStream();
1507 +            ObjectOutputStream oos = new ObjectOutputStream(bos);
1508 +            oos.writeObject(o);
1509 +            oos.flush();
1510 +            oos.close();
1511 +            return bos.toByteArray();
1512 +        } catch (Throwable fail) {
1513 +            threadUnexpectedException(fail);
1514 +            return new byte[0];
1515 +        }
1516 +    }
1517 +
1518 +    @SuppressWarnings("unchecked")
1519 +    <T> T serialClone(T o) {
1520 +        try {
1521 +            ObjectInputStream ois = new ObjectInputStream
1522 +                (new ByteArrayInputStream(serialBytes(o)));
1523 +            T clone = (T) ois.readObject();
1524 +            assertSame(o.getClass(), clone.getClass());
1525 +            return clone;
1526 +        } catch (Throwable fail) {
1527 +            threadUnexpectedException(fail);
1528 +            return null;
1529 +        }
1530 +    }
1531 +
1532 +    public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1533 +                             Runnable... throwingActions) {
1534 +        for (Runnable throwingAction : throwingActions) {
1535 +            boolean threw = false;
1536 +            try { throwingAction.run(); }
1537 +            catch (Throwable t) {
1538 +                threw = true;
1539 +                if (!expectedExceptionClass.isInstance(t)) {
1540 +                    AssertionFailedError afe =
1541 +                        new AssertionFailedError
1542 +                        ("Expected " + expectedExceptionClass.getName() +
1543 +                         ", got " + t.getClass().getName());
1544 +                    afe.initCause(t);
1545 +                    threadUnexpectedException(afe);
1546 +                }
1547 +            }
1548 +            if (!threw)
1549 +                shouldThrow(expectedExceptionClass.getName());
1550 +        }
1551 +    }
1552 +
1553 +    public void assertIteratorExhausted(Iterator<?> it) {
1554 +        try {
1555 +            it.next();
1556 +            shouldThrow();
1557 +        } catch (NoSuchElementException success) {}
1558 +        assertFalse(it.hasNext());
1559 +    }
1560   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines