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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines