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.15 by dl, Mon Dec 29 19:05:40 2003 UTC vs.
Revision 1.139 by jsr166, Sun Sep 6 21:14:12 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
5 < * Other contributors include Andrew Wright, Jeffrey Hayes,
6 < * Pat Fisher, Mike Judd.
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.*;
12 < import java.io.*;
13 < import java.security.*;
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;
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,
62   * utility methods and classes, as well as a simple framework for
63   * helping to make sure that assertions failing in generated threads
64   * cause the associated test that generated them to itself fail (which
65 < * JUnit doe not otherwise arrange).  The rules for creating such
65 > * JUnit does not otherwise arrange).  The rules for creating such
66   * tests are:
67   *
68   * <ol>
69   *
70   * <li> All assertions in code running in generated threads must use
71 < * the forms {@link threadFail} , {@link threadAssertTrue} {@link
72 < * threadAssertEquals}, or {@link threadAssertNull}, (not
73 < * <tt>fail</tt>, <tt>assertTrue</tt>, etc.) It is OK (but not
71 > * the forms {@link #threadFail}, {@link #threadAssertTrue}, {@link
72 > * #threadAssertEquals}, or {@link #threadAssertNull}, (not
73 > * {@code fail}, {@code assertTrue}, etc.) It is OK (but not
74   * particularly recommended) for other code to use these forms too.
75   * Only the most typically used JUnit assertion methods are defined
76   * this way, but enough to live with.</li>
77   *
78 < * <li> If you override {@link setUp} or {@link tearDown}, make sure
79 < * to invoke <tt>super.setUp</tt> and <tt>super.tearDown</tt> within
78 > * <li> If you override {@link #setUp} or {@link #tearDown}, make sure
79 > * to invoke {@code super.setUp} and {@code super.tearDown} within
80   * them. These methods are used to clear and check for thread
81   * assertion failures.</li>
82   *
83 < * <li>All delays and timeouts must use one of the constants <tt>
84 < * SHORT_DELAY_MS</tt>, <tt> SMALL_DELAY_MS</tt>, <tt> MEDIUM_DELAY_MS</tt>,
85 < * <tt> LONG_DELAY_MS</tt>. The idea here is that a SHORT is always
83 > * <li>All delays and timeouts must use one of the constants {@code
84 > * SHORT_DELAY_MS}, {@code SMALL_DELAY_MS}, {@code MEDIUM_DELAY_MS},
85 > * {@code LONG_DELAY_MS}. The idea here is that a SHORT is always
86   * discriminable from zero time, and always allows enough time for the
87   * small amounts of computation (creating a thread, calling a few
88   * methods, etc) needed to reach a timeout point. Similarly, a SMALL
89   * is always discriminable as larger than SHORT and smaller than
90   * MEDIUM.  And so on. These constants are set to conservative values,
91   * but even so, if there is ever any doubt, they can all be increased
92 < * in one spot to rerun tests on slower platforms</li>
92 > * in one spot to rerun tests on slower platforms.</li>
93   *
94   * <li> All threads generated must be joined inside each test case
95 < * method (or <tt>fail</tt> to do so) before returning from the
96 < * method. The <tt> joinPool</tt> method can be used to do this when
95 > * method (or {@code fail} to do so) before returning from the
96 > * method. The {@code joinPool} method can be used to do this when
97   * using Executors.</li>
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 63 | Line 108 | import java.security.*;
108   * "normal" behaviors differ significantly. And sometimes testcases
109   * cover multiple methods when they cannot be tested in
110   * isolation.</li>
111 < *
111 > *
112   * <li> The documentation style for testcases is to provide as javadoc
113   * a simple sentence or two describing the property that the testcase
114   * method purports to test. The javadocs do not say anything about how
# Line 80 | Line 125 | import java.security.*;
125   * any particular package to simplify things for people integrating
126   * them in TCK test suites.</li>
127   *
128 < * <li> As a convenience, the <tt>main</tt> of this class (JSR166TestCase)
128 > * <li> As a convenience, the {@code main} of this class (JSR166TestCase)
129   * runs all JSR166 unit tests.</li>
130   *
131   * </ul>
132   */
133   public class JSR166TestCase extends TestCase {
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
178 <     */
179 <    public static void main (String[] args) {
180 <        junit.textui.TestRunner.run (suite());
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 >        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 >    }
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
298 <     */
299 <    public static Test suite ( ) {
300 <        TestSuite suite = new TestSuite("JSR166 Unit Tests");
301 <        
302 <        suite.addTest(new TestSuite(AbstractExecutorServiceTest.class));
303 <        suite.addTest(new TestSuite(AbstractQueuedSynchronizerTest.class));
304 <        suite.addTest(new TestSuite(ArrayBlockingQueueTest.class));
305 <        suite.addTest(new TestSuite(AtomicBooleanTest.class));
306 <        suite.addTest(new TestSuite(AtomicIntegerArrayTest.class));
307 <        suite.addTest(new TestSuite(AtomicIntegerFieldUpdaterTest.class));
308 <        suite.addTest(new TestSuite(AtomicIntegerTest.class));
309 <        suite.addTest(new TestSuite(AtomicLongArrayTest.class));
310 <        suite.addTest(new TestSuite(AtomicLongFieldUpdaterTest.class));
311 <        suite.addTest(new TestSuite(AtomicLongTest.class));
312 <        suite.addTest(new TestSuite(AtomicMarkableReferenceTest.class));
313 <        suite.addTest(new TestSuite(AtomicReferenceArrayTest.class));
314 <        suite.addTest(new TestSuite(AtomicReferenceFieldUpdaterTest.class));
315 <        suite.addTest(new TestSuite(AtomicReferenceTest.class));
316 <        suite.addTest(new TestSuite(AtomicStampedReferenceTest.class));
317 <        suite.addTest(new TestSuite(ConcurrentHashMapTest.class));
318 <        suite.addTest(new TestSuite(ConcurrentLinkedQueueTest.class));
319 <        suite.addTest(new TestSuite(CopyOnWriteArrayListTest.class));
320 <        suite.addTest(new TestSuite(CopyOnWriteArraySetTest.class));
321 <        suite.addTest(new TestSuite(CountDownLatchTest.class));
322 <        suite.addTest(new TestSuite(CyclicBarrierTest.class));
323 <        suite.addTest(new TestSuite(DelayQueueTest.class));
324 <        suite.addTest(new TestSuite(ExchangerTest.class));
325 <        suite.addTest(new TestSuite(ExecutorsTest.class));
326 <        suite.addTest(new TestSuite(ExecutorCompletionServiceTest.class));
327 <        suite.addTest(new TestSuite(FutureTaskTest.class));
328 <        suite.addTest(new TestSuite(LinkedBlockingQueueTest.class));
329 <        suite.addTest(new TestSuite(LinkedListTest.class));
330 <        suite.addTest(new TestSuite(LockSupportTest.class));
331 <        suite.addTest(new TestSuite(PriorityBlockingQueueTest.class));
332 <        suite.addTest(new TestSuite(PriorityQueueTest.class));
333 <        suite.addTest(new TestSuite(ReentrantLockTest.class));
334 <        suite.addTest(new TestSuite(ReentrantReadWriteLockTest.class));
335 <        suite.addTest(new TestSuite(ScheduledExecutorTest.class));
336 <        suite.addTest(new TestSuite(SemaphoreTest.class));
337 <        suite.addTest(new TestSuite(SynchronousQueueTest.class));
338 <        suite.addTest(new TestSuite(SystemTest.class));
339 <        suite.addTest(new TestSuite(ThreadLocalTest.class));
340 <        suite.addTest(new TestSuite(ThreadPoolExecutorTest.class));
341 <        suite.addTest(new TestSuite(ThreadTest.class));
342 <        suite.addTest(new TestSuite(TimeUnitTest.class));
343 <                
297 >     * Collects all JSR166 unit tests as one suite.
298 >     */
299 >    public static Test suite() {
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 >                "ThreadLocalRandom8Test",
383 >            };
384 >            addNamedTestClasses(suite, java8TestClassNames);
385 >        }
386 >
387 >        // Java9+ test classes
388 >        if (atLeastJava9()) {
389 >            String[] java9TestClassNames = {
390 >                // Currently empty
391 >            };
392 >            addNamedTestClasses(suite, java9TestClassNames);
393 >        }
394 >
395          return suite;
396      }
397  
398 +    /** Returns list of junit-style test method names in given class. */
399 +    public static ArrayList<String> testMethodNames(Class<?> testClass) {
400 +        Method[] methods = testClass.getDeclaredMethods();
401 +        ArrayList<String> names = new ArrayList<String>(methods.length);
402 +        for (Method method : methods) {
403 +            if (method.getName().startsWith("test")
404 +                && Modifier.isPublic(method.getModifiers())
405 +                // method.getParameterCount() requires jdk8+
406 +                && method.getParameterTypes().length == 0) {
407 +                names.add(method.getName());
408 +            }
409 +        }
410 +        return names;
411 +    }
412 +
413 +    /**
414 +     * Returns junit-style testSuite for the given test class, but
415 +     * parameterized by passing extra data to each test.
416 +     */
417 +    public static <ExtraData> Test parameterizedTestSuite
418 +        (Class<? extends JSR166TestCase> testClass,
419 +         Class<ExtraData> dataClass,
420 +         ExtraData data) {
421 +        try {
422 +            TestSuite suite = new TestSuite();
423 +            Constructor c =
424 +                testClass.getDeclaredConstructor(dataClass, String.class);
425 +            for (String methodName : testMethodNames(testClass))
426 +                suite.addTest((Test) c.newInstance(data, methodName));
427 +            return suite;
428 +        } catch (Exception e) {
429 +            throw new Error(e);
430 +        }
431 +    }
432 +
433 +    /**
434 +     * Returns junit-style testSuite for the jdk8 extension of the
435 +     * given test class, but parameterized by passing extra data to
436 +     * each test.  Uses reflection to allow compilation in jdk7.
437 +     */
438 +    public static <ExtraData> Test jdk8ParameterizedTestSuite
439 +        (Class<? extends JSR166TestCase> testClass,
440 +         Class<ExtraData> dataClass,
441 +         ExtraData data) {
442 +        if (atLeastJava8()) {
443 +            String name = testClass.getName();
444 +            String name8 = name.replaceAll("Test$", "8Test");
445 +            if (name.equals(name8)) throw new Error(name);
446 +            try {
447 +                return (Test)
448 +                    Class.forName(name8)
449 +                    .getMethod("testSuite", new Class[] { dataClass })
450 +                    .invoke(null, data);
451 +            } catch (Exception e) {
452 +                throw new Error(e);
453 +            }
454 +        } else {
455 +            return new TestSuite();
456 +        }
457 +
458 +    }
459 +
460 +    // Delays for timing-dependent tests, in milliseconds.
461  
462      public static long SHORT_DELAY_MS;
463      public static long SMALL_DELAY_MS;
464      public static long MEDIUM_DELAY_MS;
465      public static long LONG_DELAY_MS;
466  
153
467      /**
468 <     * Return the shortest timed delay. This could
468 >     * Returns the shortest timed delay. This could
469       * be reimplemented to use for example a Property.
470 <     */
470 >     */
471      protected long getShortDelay() {
472 <        return 100;
472 >        return 50;
473      }
474  
162
475      /**
476 <     * Set delays as multiples of SHORT_DELAY.
476 >     * Sets delays as multiples of SHORT_DELAY.
477       */
478 <    protected  void setDelays() {
478 >    protected void setDelays() {
479          SHORT_DELAY_MS = getShortDelay();
480 <        SMALL_DELAY_MS = SHORT_DELAY_MS * 5;
480 >        SMALL_DELAY_MS  = SHORT_DELAY_MS * 5;
481          MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
482 <        LONG_DELAY_MS = SHORT_DELAY_MS * 50;
482 >        LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
483 >    }
484 >
485 >    /**
486 >     * Returns a timeout in milliseconds to be used in tests that
487 >     * verify that operations block or time out.
488 >     */
489 >    long timeoutMillis() {
490 >        return SHORT_DELAY_MS / 4;
491      }
492  
493      /**
494 <     * Flag set true if any threadAssert methods fail
494 >     * Returns a new Date instance representing a time at least
495 >     * delayMillis milliseconds in the future.
496       */
497 <    volatile boolean threadFailed;
497 >    Date delayedDate(long delayMillis) {
498 >        // Add 1 because currentTimeMillis is known to round into the past.
499 >        return new Date(System.currentTimeMillis() + delayMillis + 1);
500 >    }
501  
502      /**
503 <     * Initialize test to indicate that no thread assertions have failed
503 >     * The first exception encountered if any threadAssertXXX method fails.
504       */
505 <    public void setUp() {
505 >    private final AtomicReference<Throwable> threadFailure
506 >        = new AtomicReference<Throwable>(null);
507 >
508 >    /**
509 >     * Records an exception so that it can be rethrown later in the test
510 >     * harness thread, triggering a test case failure.  Only the first
511 >     * failure is recorded; subsequent calls to this method from within
512 >     * the same test have no effect.
513 >     */
514 >    public void threadRecordFailure(Throwable t) {
515 >        threadFailure.compareAndSet(null, t);
516 >    }
517 >
518 >    public void setUp() {
519          setDelays();
183        threadFailed = false;  
520      }
521  
522      /**
523 <     * Trigger test case failure if any thread assertions have failed
523 >     * Extra checks that get done for all test cases.
524 >     *
525 >     * Triggers test case failure if any thread assertions have failed,
526 >     * by rethrowing, in the test harness thread, any exception recorded
527 >     * earlier by threadRecordFailure.
528 >     *
529 >     * Triggers test case failure if interrupt status is set in the main thread.
530       */
531 <    public void tearDown() {
532 <        assertFalse(threadFailed);  
531 >    public void tearDown() throws Exception {
532 >        Throwable t = threadFailure.getAndSet(null);
533 >        if (t != null) {
534 >            if (t instanceof Error)
535 >                throw (Error) t;
536 >            else if (t instanceof RuntimeException)
537 >                throw (RuntimeException) t;
538 >            else if (t instanceof Exception)
539 >                throw (Exception) t;
540 >            else {
541 >                AssertionFailedError afe =
542 >                    new AssertionFailedError(t.toString());
543 >                afe.initCause(t);
544 >                throw afe;
545 >            }
546 >        }
547 >
548 >        if (Thread.interrupted())
549 >            throw new AssertionFailedError("interrupt status set in main thread");
550 >
551 >        checkForkJoinPoolThreadLeaks();
552      }
553  
554      /**
555 <     * Fail, also setting status to indicate current testcase should fail
556 <     */
555 >     * Finds missing try { ... } finally { joinPool(e); }
556 >     */
557 >    void checkForkJoinPoolThreadLeaks() throws InterruptedException {
558 >        Thread[] survivors = new Thread[5];
559 >        int count = Thread.enumerate(survivors);
560 >        for (int i = 0; i < count; i++) {
561 >            Thread thread = survivors[i];
562 >            String name = thread.getName();
563 >            if (name.startsWith("ForkJoinPool-")) {
564 >                // give thread some time to terminate
565 >                thread.join(LONG_DELAY_MS);
566 >                if (!thread.isAlive()) continue;
567 >                throw new AssertionFailedError
568 >                    (String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n",
569 >                                   toString(), name));
570 >            }
571 >        }
572 >    }
573 >
574 >    /**
575 >     * Just like fail(reason), but additionally recording (using
576 >     * threadRecordFailure) any AssertionFailedError thrown, so that
577 >     * the current testcase will fail.
578 >     */
579      public void threadFail(String reason) {
580 <        threadFailed = true;
581 <        fail(reason);
580 >        try {
581 >            fail(reason);
582 >        } catch (AssertionFailedError t) {
583 >            threadRecordFailure(t);
584 >            fail(reason);
585 >        }
586      }
587  
588      /**
589 <     * If expression not true, set status to indicate current testcase
590 <     * should fail
591 <     */
589 >     * Just like assertTrue(b), but additionally recording (using
590 >     * threadRecordFailure) any AssertionFailedError thrown, so that
591 >     * the current testcase will fail.
592 >     */
593      public void threadAssertTrue(boolean b) {
594 <        if (!b) {
207 <            threadFailed = true;
594 >        try {
595              assertTrue(b);
596 +        } catch (AssertionFailedError t) {
597 +            threadRecordFailure(t);
598 +            throw t;
599          }
600      }
601  
602      /**
603 <     * If expression not false, set status to indicate current testcase
604 <     * should fail
605 <     */
603 >     * Just like assertFalse(b), but additionally recording (using
604 >     * threadRecordFailure) any AssertionFailedError thrown, so that
605 >     * the current testcase will fail.
606 >     */
607      public void threadAssertFalse(boolean b) {
608 <        if (b) {
218 <            threadFailed = true;
608 >        try {
609              assertFalse(b);
610 +        } catch (AssertionFailedError t) {
611 +            threadRecordFailure(t);
612 +            throw t;
613          }
614      }
615  
616      /**
617 <     * If argument not null, set status to indicate current testcase
618 <     * should fail
619 <     */
617 >     * Just like assertNull(x), but additionally recording (using
618 >     * threadRecordFailure) any AssertionFailedError thrown, so that
619 >     * the current testcase will fail.
620 >     */
621      public void threadAssertNull(Object x) {
622 <        if (x != null) {
229 <            threadFailed = true;
622 >        try {
623              assertNull(x);
624 +        } catch (AssertionFailedError t) {
625 +            threadRecordFailure(t);
626 +            throw t;
627          }
628      }
629  
630      /**
631 <     * If arguments not equal, set status to indicate current testcase
632 <     * should fail
633 <     */
631 >     * Just like assertEquals(x, y), but additionally recording (using
632 >     * threadRecordFailure) any AssertionFailedError thrown, so that
633 >     * the current testcase will fail.
634 >     */
635      public void threadAssertEquals(long x, long y) {
636 <        if (x != y) {
240 <            threadFailed = true;
636 >        try {
637              assertEquals(x, y);
638 +        } catch (AssertionFailedError t) {
639 +            threadRecordFailure(t);
640 +            throw t;
641          }
642      }
643  
644      /**
645 <     * If arguments not equal, set status to indicate current testcase
646 <     * should fail
647 <     */
645 >     * Just like assertEquals(x, y), but additionally recording (using
646 >     * threadRecordFailure) any AssertionFailedError thrown, so that
647 >     * the current testcase will fail.
648 >     */
649      public void threadAssertEquals(Object x, Object y) {
650 <        if (x != y && (x == null || !x.equals(y))) {
251 <            threadFailed = true;
650 >        try {
651              assertEquals(x, y);
652 +        } catch (AssertionFailedError fail) {
653 +            threadRecordFailure(fail);
654 +            throw fail;
655 +        } catch (Throwable fail) {
656 +            threadUnexpectedException(fail);
657 +        }
658 +    }
659 +
660 +    /**
661 +     * Just like assertSame(x, y), but additionally recording (using
662 +     * threadRecordFailure) any AssertionFailedError thrown, so that
663 +     * the current testcase will fail.
664 +     */
665 +    public void threadAssertSame(Object x, Object y) {
666 +        try {
667 +            assertSame(x, y);
668 +        } catch (AssertionFailedError fail) {
669 +            threadRecordFailure(fail);
670 +            throw fail;
671          }
672      }
673  
674      /**
675 <     * threadFail with message "should throw exception"
676 <     */
675 >     * Calls threadFail with message "should throw exception".
676 >     */
677      public void threadShouldThrow() {
678 <        threadFailed = true;
261 <        fail("should throw exception");
678 >        threadFail("should throw exception");
679      }
680  
681      /**
682 <     * threadFail with message "Unexpected exception"
682 >     * Calls threadFail with message "should throw" + exceptionName.
683       */
684 <    public void threadUnexpectedException() {
685 <        threadFailed = true;
269 <        fail("Unexpected exception");
684 >    public void threadShouldThrow(String exceptionName) {
685 >        threadFail("should throw " + exceptionName);
686      }
687  
688 +    /**
689 +     * Records the given exception using {@link #threadRecordFailure},
690 +     * then rethrows the exception, wrapping it in an
691 +     * AssertionFailedError if necessary.
692 +     */
693 +    public void threadUnexpectedException(Throwable t) {
694 +        threadRecordFailure(t);
695 +        t.printStackTrace();
696 +        if (t instanceof RuntimeException)
697 +            throw (RuntimeException) t;
698 +        else if (t instanceof Error)
699 +            throw (Error) t;
700 +        else {
701 +            AssertionFailedError afe =
702 +                new AssertionFailedError("unexpected exception: " + t);
703 +            afe.initCause(t);
704 +            throw afe;
705 +        }
706 +    }
707 +
708 +    /**
709 +     * Delays, via Thread.sleep, for the given millisecond delay, but
710 +     * if the sleep is shorter than specified, may re-sleep or yield
711 +     * until time elapses.
712 +     */
713 +    static void delay(long millis) throws InterruptedException {
714 +        long startTime = System.nanoTime();
715 +        long ns = millis * 1000 * 1000;
716 +        for (;;) {
717 +            if (millis > 0L)
718 +                Thread.sleep(millis);
719 +            else // too short to sleep
720 +                Thread.yield();
721 +            long d = ns - (System.nanoTime() - startTime);
722 +            if (d > 0L)
723 +                millis = d / (1000 * 1000);
724 +            else
725 +                break;
726 +        }
727 +    }
728  
729      /**
730 <     * Wait out termination of a thread pool or fail doing so
730 >     * Waits out termination of a thread pool or fails doing so.
731       */
732 <    public void joinPool(ExecutorService exec) {
732 >    void joinPool(ExecutorService pool) {
733          try {
734 <            exec.shutdown();
735 <            assertTrue(exec.awaitTermination(LONG_DELAY_MS, TimeUnit.MILLISECONDS));
736 <        } catch(InterruptedException ie) {
737 <            fail("Unexpected exception");
734 >            pool.shutdown();
735 >            if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS))
736 >                fail("ExecutorService " + pool +
737 >                     " did not terminate in a timely manner");
738 >        } catch (SecurityException ok) {
739 >            // Allowed in case test doesn't have privs
740 >        } catch (InterruptedException fail) {
741 >            fail("Unexpected InterruptedException");
742          }
743      }
744  
745 +    /** Like Runnable, but with the freedom to throw anything */
746 +    interface Thunk { public void run() throws Throwable; }
747 +
748 +    /**
749 +     * Runs all the given tasks in parallel, failing if any fail.
750 +     * Useful for running multiple variants of tests that are
751 +     * necessarily individually slow because they must block.
752 +     */
753 +    void testInParallel(Thunk ... thunks) {
754 +        ExecutorService pool = Executors.newCachedThreadPool();
755 +        try {
756 +            ArrayList<Future<?>> futures = new ArrayList<>(thunks.length);
757 +            for (final Thunk thunk : thunks)
758 +                futures.add(pool.submit(new CheckedRunnable() {
759 +                    public void realRun() throws Throwable { thunk.run();}}));
760 +            for (Future<?> future : futures)
761 +                try {
762 +                    assertNull(future.get(LONG_DELAY_MS, MILLISECONDS));
763 +                } catch (ExecutionException ex) {
764 +                    threadUnexpectedException(ex.getCause());
765 +                } catch (Exception ex) {
766 +                    threadUnexpectedException(ex);
767 +                }
768 +        } finally {
769 +            joinPool(pool);
770 +        }
771 +    }
772 +
773 +    /**
774 +     * A debugging tool to print all stack traces, as jstack does.
775 +     */
776 +    static void printAllStackTraces() {
777 +        for (ThreadInfo info :
778 +                 ManagementFactory.getThreadMXBean()
779 +                 .dumpAllThreads(true, true))
780 +            System.err.print(info);
781 +    }
782 +
783 +    /**
784 +     * Checks that thread does not terminate within the default
785 +     * millisecond delay of {@code timeoutMillis()}.
786 +     */
787 +    void assertThreadStaysAlive(Thread thread) {
788 +        assertThreadStaysAlive(thread, timeoutMillis());
789 +    }
790  
791      /**
792 <     * fail with message "should throw exception"
793 <     */
792 >     * Checks that thread does not terminate within the given millisecond delay.
793 >     */
794 >    void assertThreadStaysAlive(Thread thread, long millis) {
795 >        try {
796 >            // No need to optimize the failing case via Thread.join.
797 >            delay(millis);
798 >            assertTrue(thread.isAlive());
799 >        } catch (InterruptedException fail) {
800 >            fail("Unexpected InterruptedException");
801 >        }
802 >    }
803 >
804 >    /**
805 >     * Checks that the threads do not terminate within the default
806 >     * millisecond delay of {@code timeoutMillis()}.
807 >     */
808 >    void assertThreadsStayAlive(Thread... threads) {
809 >        assertThreadsStayAlive(timeoutMillis(), threads);
810 >    }
811 >
812 >    /**
813 >     * Checks that the threads do not terminate within the given millisecond delay.
814 >     */
815 >    void assertThreadsStayAlive(long millis, Thread... threads) {
816 >        try {
817 >            // No need to optimize the failing case via Thread.join.
818 >            delay(millis);
819 >            for (Thread thread : threads)
820 >                assertTrue(thread.isAlive());
821 >        } catch (InterruptedException fail) {
822 >            fail("Unexpected InterruptedException");
823 >        }
824 >    }
825 >
826 >    /**
827 >     * Checks that future.get times out, with the default timeout of
828 >     * {@code timeoutMillis()}.
829 >     */
830 >    void assertFutureTimesOut(Future future) {
831 >        assertFutureTimesOut(future, timeoutMillis());
832 >    }
833 >
834 >    /**
835 >     * Checks that future.get times out, with the given millisecond timeout.
836 >     */
837 >    void assertFutureTimesOut(Future future, long timeoutMillis) {
838 >        long startTime = System.nanoTime();
839 >        try {
840 >            future.get(timeoutMillis, MILLISECONDS);
841 >            shouldThrow();
842 >        } catch (TimeoutException success) {
843 >        } catch (Exception fail) {
844 >            threadUnexpectedException(fail);
845 >        } finally { future.cancel(true); }
846 >        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
847 >    }
848 >
849 >    /**
850 >     * Fails with message "should throw exception".
851 >     */
852      public void shouldThrow() {
853          fail("Should throw exception");
854      }
855  
856      /**
857 <     * fail with message "Unexpected exception"
857 >     * Fails with message "should throw " + exceptionName.
858       */
859 <    public void unexpectedException() {
860 <        fail("Unexpected exception");
859 >    public void shouldThrow(String exceptionName) {
860 >        fail("Should throw " + exceptionName);
861      }
862  
300
863      /**
864       * The number of elements to place in collections, arrays, etc.
865       */
866 <    static final int SIZE = 20;
866 >    public static final int SIZE = 20;
867  
868      // Some convenient Integer constants
869  
870 <    static final Integer zero = new Integer(0);
871 <    static final Integer one = new Integer(1);
872 <    static final Integer two = new Integer(2);
873 <    static final Integer three  = new Integer(3);
874 <    static final Integer four  = new Integer(4);
875 <    static final Integer five  = new Integer(5);
876 <    static final Integer six = new Integer(6);
877 <    static final Integer seven = new Integer(7);
878 <    static final Integer eight = new Integer(8);
879 <    static final Integer nine = new Integer(9);
880 <    static final Integer m1  = new Integer(-1);
881 <    static final Integer m2  = new Integer(-2);
882 <    static final Integer m3  = new Integer(-3);
883 <    static final Integer m4 = new Integer(-4);
884 <    static final Integer m5 = new Integer(-5);
885 <    static final Integer m10 = new Integer(-10);
870 >    public static final Integer zero  = new Integer(0);
871 >    public static final Integer one   = new Integer(1);
872 >    public static final Integer two   = new Integer(2);
873 >    public static final Integer three = new Integer(3);
874 >    public static final Integer four  = new Integer(4);
875 >    public static final Integer five  = new Integer(5);
876 >    public static final Integer six   = new Integer(6);
877 >    public static final Integer seven = new Integer(7);
878 >    public static final Integer eight = new Integer(8);
879 >    public static final Integer nine  = new Integer(9);
880 >    public static final Integer m1  = new Integer(-1);
881 >    public static final Integer m2  = new Integer(-2);
882 >    public static final Integer m3  = new Integer(-3);
883 >    public static final Integer m4  = new Integer(-4);
884 >    public static final Integer m5  = new Integer(-5);
885 >    public static final Integer m6  = new Integer(-6);
886 >    public static final Integer m10 = new Integer(-10);
887 >
888 >    /**
889 >     * Runs Runnable r with a security policy that permits precisely
890 >     * the specified permissions.  If there is no current security
891 >     * manager, the runnable is run twice, both with and without a
892 >     * security manager.  We require that any security manager permit
893 >     * getPolicy/setPolicy.
894 >     */
895 >    public void runWithPermissions(Runnable r, Permission... permissions) {
896 >        SecurityManager sm = System.getSecurityManager();
897 >        if (sm == null) {
898 >            r.run();
899 >        }
900 >        runWithSecurityManagerWithPermissions(r, permissions);
901 >    }
902  
903 +    /**
904 +     * Runs Runnable r with a security policy that permits precisely
905 +     * the specified permissions.  If there is no current security
906 +     * manager, a temporary one is set for the duration of the
907 +     * Runnable.  We require that any security manager permit
908 +     * getPolicy/setPolicy.
909 +     */
910 +    public void runWithSecurityManagerWithPermissions(Runnable r,
911 +                                                      Permission... permissions) {
912 +        SecurityManager sm = System.getSecurityManager();
913 +        if (sm == null) {
914 +            Policy savedPolicy = Policy.getPolicy();
915 +            try {
916 +                Policy.setPolicy(permissivePolicy());
917 +                System.setSecurityManager(new SecurityManager());
918 +                runWithSecurityManagerWithPermissions(r, permissions);
919 +            } finally {
920 +                System.setSecurityManager(null);
921 +                Policy.setPolicy(savedPolicy);
922 +            }
923 +        } else {
924 +            Policy savedPolicy = Policy.getPolicy();
925 +            AdjustablePolicy policy = new AdjustablePolicy(permissions);
926 +            Policy.setPolicy(policy);
927 +
928 +            try {
929 +                r.run();
930 +            } finally {
931 +                policy.addPermission(new SecurityPermission("setPolicy"));
932 +                Policy.setPolicy(savedPolicy);
933 +            }
934 +        }
935 +    }
936 +
937 +    /**
938 +     * Runs a runnable without any permissions.
939 +     */
940 +    public void runWithoutPermissions(Runnable r) {
941 +        runWithPermissions(r);
942 +    }
943  
944      /**
945       * A security policy where new permissions can be dynamically added
946       * or all cleared.
947       */
948 <    static class AdjustablePolicy extends java.security.Policy {
948 >    public static class AdjustablePolicy extends java.security.Policy {
949          Permissions perms = new Permissions();
950 <        AdjustablePolicy() { }
950 >        AdjustablePolicy(Permission... permissions) {
951 >            for (Permission permission : permissions)
952 >                perms.add(permission);
953 >        }
954          void addPermission(Permission perm) { perms.add(perm); }
955          void clearPermissions() { perms = new Permissions(); }
956 <        public PermissionCollection getPermissions(CodeSource cs) {
957 <            return perms;
958 <        }
959 <        public PermissionCollection getPermissions(ProtectionDomain pd) {
960 <            return perms;
961 <        }
962 <        public boolean implies(ProtectionDomain pd, Permission p) {
963 <            return perms.implies(p);
964 <        }
965 <        public void refresh() {}
956 >        public PermissionCollection getPermissions(CodeSource cs) {
957 >            return perms;
958 >        }
959 >        public PermissionCollection getPermissions(ProtectionDomain pd) {
960 >            return perms;
961 >        }
962 >        public boolean implies(ProtectionDomain pd, Permission p) {
963 >            return perms.implies(p);
964 >        }
965 >        public void refresh() {}
966 >        public String toString() {
967 >            List<Permission> ps = new ArrayList<Permission>();
968 >            for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
969 >                ps.add(e.nextElement());
970 >            return "AdjustablePolicy with permissions " + ps;
971 >        }
972      }
973  
974 +    /**
975 +     * Returns a policy containing all the permissions we ever need.
976 +     */
977 +    public static Policy permissivePolicy() {
978 +        return new AdjustablePolicy
979 +            // Permissions j.u.c. needs directly
980 +            (new RuntimePermission("modifyThread"),
981 +             new RuntimePermission("getClassLoader"),
982 +             new RuntimePermission("setContextClassLoader"),
983 +             // Permissions needed to change permissions!
984 +             new SecurityPermission("getPolicy"),
985 +             new SecurityPermission("setPolicy"),
986 +             new RuntimePermission("setSecurityManager"),
987 +             // Permissions needed by the junit test harness
988 +             new RuntimePermission("accessDeclaredMembers"),
989 +             new PropertyPermission("*", "read"),
990 +             new java.io.FilePermission("<<ALL FILES>>", "read"));
991 +    }
992  
993 <    // Some convenient Runnable classes
993 >    /**
994 >     * Sleeps until the given time has elapsed.
995 >     * Throws AssertionFailedError if interrupted.
996 >     */
997 >    void sleep(long millis) {
998 >        try {
999 >            delay(millis);
1000 >        } catch (InterruptedException fail) {
1001 >            AssertionFailedError afe =
1002 >                new AssertionFailedError("Unexpected InterruptedException");
1003 >            afe.initCause(fail);
1004 >            throw afe;
1005 >        }
1006 >    }
1007  
1008 <    static class NoOpRunnable implements Runnable {
1009 <        public void run() {}
1008 >    /**
1009 >     * Spin-waits up to the specified number of milliseconds for the given
1010 >     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1011 >     */
1012 >    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
1013 >        long startTime = System.nanoTime();
1014 >        for (;;) {
1015 >            Thread.State s = thread.getState();
1016 >            if (s == Thread.State.BLOCKED ||
1017 >                s == Thread.State.WAITING ||
1018 >                s == Thread.State.TIMED_WAITING)
1019 >                return;
1020 >            else if (s == Thread.State.TERMINATED)
1021 >                fail("Unexpected thread termination");
1022 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
1023 >                threadAssertTrue(thread.isAlive());
1024 >                return;
1025 >            }
1026 >            Thread.yield();
1027 >        }
1028      }
1029  
1030 <    static class NoOpCallable implements Callable {
1031 <        public Object call() { return Boolean.TRUE; }
1030 >    /**
1031 >     * Waits up to LONG_DELAY_MS for the given thread to enter a wait
1032 >     * state: BLOCKED, WAITING, or TIMED_WAITING.
1033 >     */
1034 >    void waitForThreadToEnterWaitState(Thread thread) {
1035 >        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
1036      }
1037  
1038 <    static final String TEST_STRING = "a test string";
1038 >    /**
1039 >     * Returns the number of milliseconds since time given by
1040 >     * startNanoTime, which must have been previously returned from a
1041 >     * call to {@link System#nanoTime()}.
1042 >     */
1043 >    static long millisElapsedSince(long startNanoTime) {
1044 >        return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
1045 >    }
1046  
1047 <    static class StringTask implements Callable<String> {
1048 <        public String call() { return TEST_STRING; }
1047 > //     void assertTerminatesPromptly(long timeoutMillis, Runnable r) {
1048 > //         long startTime = System.nanoTime();
1049 > //         try {
1050 > //             r.run();
1051 > //         } catch (Throwable fail) { threadUnexpectedException(fail); }
1052 > //         if (millisElapsedSince(startTime) > timeoutMillis/2)
1053 > //             throw new AssertionFailedError("did not return promptly");
1054 > //     }
1055 >
1056 > //     void assertTerminatesPromptly(Runnable r) {
1057 > //         assertTerminatesPromptly(LONG_DELAY_MS/2, r);
1058 > //     }
1059 >
1060 >    /**
1061 >     * Checks that timed f.get() returns the expected value, and does not
1062 >     * wait for the timeout to elapse before returning.
1063 >     */
1064 >    <T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) {
1065 >        long startTime = System.nanoTime();
1066 >        try {
1067 >            assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
1068 >        } catch (Throwable fail) { threadUnexpectedException(fail); }
1069 >        if (millisElapsedSince(startTime) > timeoutMillis/2)
1070 >            throw new AssertionFailedError("timed get did not return promptly");
1071      }
1072  
1073 <    static class NPETask implements Callable<String> {
1074 <        public String call() { throw new NullPointerException(); }
1073 >    <T> void checkTimedGet(Future<T> f, T expectedValue) {
1074 >        checkTimedGet(f, expectedValue, LONG_DELAY_MS);
1075      }
1076  
1077 <    static class CallableOne implements Callable<Integer> {
1078 <        public Integer call() { return one; }
1077 >    /**
1078 >     * Returns a new started daemon Thread running the given runnable.
1079 >     */
1080 >    Thread newStartedThread(Runnable runnable) {
1081 >        Thread t = new Thread(runnable);
1082 >        t.setDaemon(true);
1083 >        t.start();
1084 >        return t;
1085      }
1086  
1087 <    class ShortRunnable implements Runnable {
1088 <        public void run() {
1089 <            try {
1090 <                Thread.sleep(SHORT_DELAY_MS);
1091 <            }
1092 <            catch(Exception e) {
1093 <                threadUnexpectedException();
1087 >    /**
1088 >     * Waits for the specified time (in milliseconds) for the thread
1089 >     * to terminate (using {@link Thread#join(long)}), else interrupts
1090 >     * the thread (in the hope that it may terminate later) and fails.
1091 >     */
1092 >    void awaitTermination(Thread t, long timeoutMillis) {
1093 >        try {
1094 >            t.join(timeoutMillis);
1095 >        } catch (InterruptedException fail) {
1096 >            threadUnexpectedException(fail);
1097 >        } finally {
1098 >            if (t.getState() != Thread.State.TERMINATED) {
1099 >                t.interrupt();
1100 >                fail("Test timed out");
1101              }
1102          }
1103      }
1104  
1105 <    class ShortInterruptedRunnable implements Runnable {
1106 <        public void run() {
1105 >    /**
1106 >     * Waits for LONG_DELAY_MS milliseconds for the thread to
1107 >     * terminate (using {@link Thread#join(long)}), else interrupts
1108 >     * the thread (in the hope that it may terminate later) and fails.
1109 >     */
1110 >    void awaitTermination(Thread t) {
1111 >        awaitTermination(t, LONG_DELAY_MS);
1112 >    }
1113 >
1114 >    // Some convenient Runnable classes
1115 >
1116 >    public abstract class CheckedRunnable implements Runnable {
1117 >        protected abstract void realRun() throws Throwable;
1118 >
1119 >        public final void run() {
1120              try {
1121 <                Thread.sleep(SHORT_DELAY_MS);
1122 <                threadShouldThrow();
1123 <            }
389 <            catch(InterruptedException success) {
1121 >                realRun();
1122 >            } catch (Throwable fail) {
1123 >                threadUnexpectedException(fail);
1124              }
1125          }
1126      }
1127  
1128 <    class SmallRunnable implements Runnable {
1129 <        public void run() {
1128 >    public abstract class RunnableShouldThrow implements Runnable {
1129 >        protected abstract void realRun() throws Throwable;
1130 >
1131 >        final Class<?> exceptionClass;
1132 >
1133 >        <T extends Throwable> RunnableShouldThrow(Class<T> exceptionClass) {
1134 >            this.exceptionClass = exceptionClass;
1135 >        }
1136 >
1137 >        public final void run() {
1138              try {
1139 <                Thread.sleep(SMALL_DELAY_MS);
1140 <            }
1141 <            catch(Exception e) {
1142 <                threadUnexpectedException();
1139 >                realRun();
1140 >                threadShouldThrow(exceptionClass.getSimpleName());
1141 >            } catch (Throwable t) {
1142 >                if (! exceptionClass.isInstance(t))
1143 >                    threadUnexpectedException(t);
1144              }
1145          }
1146      }
1147  
1148 <    class SmallPossiblyInterruptedRunnable implements Runnable {
1149 <        public void run() {
1148 >    public abstract class ThreadShouldThrow extends Thread {
1149 >        protected abstract void realRun() throws Throwable;
1150 >
1151 >        final Class<?> exceptionClass;
1152 >
1153 >        <T extends Throwable> ThreadShouldThrow(Class<T> exceptionClass) {
1154 >            this.exceptionClass = exceptionClass;
1155 >        }
1156 >
1157 >        public final void run() {
1158              try {
1159 <                Thread.sleep(SMALL_DELAY_MS);
1160 <            }
1161 <            catch(Exception e) {
1159 >                realRun();
1160 >                threadShouldThrow(exceptionClass.getSimpleName());
1161 >            } catch (Throwable t) {
1162 >                if (! exceptionClass.isInstance(t))
1163 >                    threadUnexpectedException(t);
1164              }
1165          }
1166      }
1167  
1168 <    class SmallCallable implements Callable {
1169 <        public Object call() {
1168 >    public abstract class CheckedInterruptedRunnable implements Runnable {
1169 >        protected abstract void realRun() throws Throwable;
1170 >
1171 >        public final void run() {
1172              try {
1173 <                Thread.sleep(SMALL_DELAY_MS);
1173 >                realRun();
1174 >                threadShouldThrow("InterruptedException");
1175 >            } catch (InterruptedException success) {
1176 >                threadAssertFalse(Thread.interrupted());
1177 >            } catch (Throwable fail) {
1178 >                threadUnexpectedException(fail);
1179              }
420            catch(Exception e) {
421                threadUnexpectedException();
422            }
423            return Boolean.TRUE;
1180          }
1181      }
1182  
1183 <    class SmallInterruptedRunnable implements Runnable {
1184 <        public void run() {
1183 >    public abstract class CheckedCallable<T> implements Callable<T> {
1184 >        protected abstract T realCall() throws Throwable;
1185 >
1186 >        public final T call() {
1187              try {
1188 <                Thread.sleep(SMALL_DELAY_MS);
1189 <                threadShouldThrow();
1190 <            }
1191 <            catch(InterruptedException success) {
1188 >                return realCall();
1189 >            } catch (Throwable fail) {
1190 >                threadUnexpectedException(fail);
1191 >                return null;
1192              }
1193          }
1194      }
1195  
1196 +    public abstract class CheckedInterruptedCallable<T>
1197 +        implements Callable<T> {
1198 +        protected abstract T realCall() throws Throwable;
1199  
1200 <    class MediumRunnable implements Runnable {
440 <        public void run() {
1200 >        public final T call() {
1201              try {
1202 <                Thread.sleep(MEDIUM_DELAY_MS);
1203 <            }
1204 <            catch(Exception e) {
1205 <                threadUnexpectedException();
1202 >                T result = realCall();
1203 >                threadShouldThrow("InterruptedException");
1204 >                return result;
1205 >            } catch (InterruptedException success) {
1206 >                threadAssertFalse(Thread.interrupted());
1207 >            } catch (Throwable fail) {
1208 >                threadUnexpectedException(fail);
1209              }
1210 +            return null;
1211          }
1212      }
1213  
1214 <    class MediumInterruptedRunnable implements Runnable {
1215 <        public void run() {
1214 >    public static class NoOpRunnable implements Runnable {
1215 >        public void run() {}
1216 >    }
1217 >
1218 >    public static class NoOpCallable implements Callable {
1219 >        public Object call() { return Boolean.TRUE; }
1220 >    }
1221 >
1222 >    public static final String TEST_STRING = "a test string";
1223 >
1224 >    public static class StringTask implements Callable<String> {
1225 >        public String call() { return TEST_STRING; }
1226 >    }
1227 >
1228 >    public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
1229 >        return new CheckedCallable<String>() {
1230 >            protected String realCall() {
1231 >                try {
1232 >                    latch.await();
1233 >                } catch (InterruptedException quittingTime) {}
1234 >                return TEST_STRING;
1235 >            }};
1236 >    }
1237 >
1238 >    public Runnable awaiter(final CountDownLatch latch) {
1239 >        return new CheckedRunnable() {
1240 >            public void realRun() throws InterruptedException {
1241 >                await(latch);
1242 >            }};
1243 >    }
1244 >
1245 >    public void await(CountDownLatch latch) {
1246 >        try {
1247 >            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1248 >        } catch (Throwable fail) {
1249 >            threadUnexpectedException(fail);
1250 >        }
1251 >    }
1252 >
1253 >    public void await(Semaphore semaphore) {
1254 >        try {
1255 >            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1256 >        } catch (Throwable fail) {
1257 >            threadUnexpectedException(fail);
1258 >        }
1259 >    }
1260 >
1261 > //     /**
1262 > //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1263 > //      */
1264 > //     public void await(AtomicBoolean flag) {
1265 > //         await(flag, LONG_DELAY_MS);
1266 > //     }
1267 >
1268 > //     /**
1269 > //      * Spin-waits up to the specified timeout until flag becomes true.
1270 > //      */
1271 > //     public void await(AtomicBoolean flag, long timeoutMillis) {
1272 > //         long startTime = System.nanoTime();
1273 > //         while (!flag.get()) {
1274 > //             if (millisElapsedSince(startTime) > timeoutMillis)
1275 > //                 throw new AssertionFailedError("timed out");
1276 > //             Thread.yield();
1277 > //         }
1278 > //     }
1279 >
1280 >    public static class NPETask implements Callable<String> {
1281 >        public String call() { throw new NullPointerException(); }
1282 >    }
1283 >
1284 >    public static class CallableOne implements Callable<Integer> {
1285 >        public Integer call() { return one; }
1286 >    }
1287 >
1288 >    public class ShortRunnable extends CheckedRunnable {
1289 >        protected void realRun() throws Throwable {
1290 >            delay(SHORT_DELAY_MS);
1291 >        }
1292 >    }
1293 >
1294 >    public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1295 >        protected void realRun() throws InterruptedException {
1296 >            delay(SHORT_DELAY_MS);
1297 >        }
1298 >    }
1299 >
1300 >    public class SmallRunnable extends CheckedRunnable {
1301 >        protected void realRun() throws Throwable {
1302 >            delay(SMALL_DELAY_MS);
1303 >        }
1304 >    }
1305 >
1306 >    public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1307 >        protected void realRun() {
1308              try {
1309 <                Thread.sleep(MEDIUM_DELAY_MS);
1310 <                threadShouldThrow();
455 <            }
456 <            catch(InterruptedException success) {
457 <            }
1309 >                delay(SMALL_DELAY_MS);
1310 >            } catch (InterruptedException ok) {}
1311          }
1312      }
1313  
1314 <    class MediumPossiblyInterruptedRunnable implements Runnable {
1315 <        public void run() {
1314 >    public class SmallCallable extends CheckedCallable {
1315 >        protected Object realCall() throws InterruptedException {
1316 >            delay(SMALL_DELAY_MS);
1317 >            return Boolean.TRUE;
1318 >        }
1319 >    }
1320 >
1321 >    public class MediumRunnable extends CheckedRunnable {
1322 >        protected void realRun() throws Throwable {
1323 >            delay(MEDIUM_DELAY_MS);
1324 >        }
1325 >    }
1326 >
1327 >    public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1328 >        protected void realRun() throws InterruptedException {
1329 >            delay(MEDIUM_DELAY_MS);
1330 >        }
1331 >    }
1332 >
1333 >    public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1334 >        return new CheckedRunnable() {
1335 >            protected void realRun() {
1336 >                try {
1337 >                    delay(timeoutMillis);
1338 >                } catch (InterruptedException ok) {}
1339 >            }};
1340 >    }
1341 >
1342 >    public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1343 >        protected void realRun() {
1344              try {
1345 <                Thread.sleep(MEDIUM_DELAY_MS);
1346 <            }
466 <            catch(InterruptedException success) {
467 <            }
1345 >                delay(MEDIUM_DELAY_MS);
1346 >            } catch (InterruptedException ok) {}
1347          }
1348      }
1349  
1350 <    class LongPossiblyInterruptedRunnable implements Runnable {
1351 <        public void run() {
1350 >    public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1351 >        protected void realRun() {
1352              try {
1353 <                Thread.sleep(LONG_DELAY_MS);
1354 <            }
476 <            catch(InterruptedException success) {
477 <            }
1353 >                delay(LONG_DELAY_MS);
1354 >            } catch (InterruptedException ok) {}
1355          }
1356      }
1357  
1358      /**
1359       * For use as ThreadFactory in constructors
1360       */
1361 <    static class SimpleThreadFactory implements ThreadFactory{
1362 <        public Thread newThread(Runnable r){
1361 >    public static class SimpleThreadFactory implements ThreadFactory {
1362 >        public Thread newThread(Runnable r) {
1363              return new Thread(r);
1364 <        }  
1364 >        }
1365 >    }
1366 >
1367 >    public interface TrackedRunnable extends Runnable {
1368 >        boolean isDone();
1369      }
1370  
1371 <    static class TrackedShortRunnable implements Runnable {
1372 <        volatile boolean done = false;
1371 >    public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
1372 >        return new TrackedRunnable() {
1373 >                private volatile boolean done = false;
1374 >                public boolean isDone() { return done; }
1375 >                public void run() {
1376 >                    try {
1377 >                        delay(timeoutMillis);
1378 >                        done = true;
1379 >                    } catch (InterruptedException ok) {}
1380 >                }
1381 >            };
1382 >    }
1383 >
1384 >    public static class TrackedShortRunnable implements Runnable {
1385 >        public volatile boolean done = false;
1386          public void run() {
1387              try {
1388 <                Thread.sleep(SMALL_DELAY_MS);
1388 >                delay(SHORT_DELAY_MS);
1389                  done = true;
1390 <            } catch(Exception e){
497 <            }
1390 >            } catch (InterruptedException ok) {}
1391          }
1392      }
1393  
1394 <    static class TrackedMediumRunnable implements Runnable {
1395 <        volatile boolean done = false;
1394 >    public static class TrackedSmallRunnable implements Runnable {
1395 >        public volatile boolean done = false;
1396          public void run() {
1397              try {
1398 <                Thread.sleep(MEDIUM_DELAY_MS);
1398 >                delay(SMALL_DELAY_MS);
1399                  done = true;
1400 <            } catch(Exception e){
508 <            }
1400 >            } catch (InterruptedException ok) {}
1401          }
1402      }
1403  
1404 <    static class TrackedLongRunnable implements Runnable {
1405 <        volatile boolean done = false;
1404 >    public static class TrackedMediumRunnable implements Runnable {
1405 >        public volatile boolean done = false;
1406          public void run() {
1407              try {
1408 <                Thread.sleep(LONG_DELAY_MS);
1408 >                delay(MEDIUM_DELAY_MS);
1409                  done = true;
1410 <            } catch(Exception e){
519 <            }
1410 >            } catch (InterruptedException ok) {}
1411          }
1412      }
1413  
1414 <    static class TrackedNoOpRunnable implements Runnable {
1415 <        volatile boolean done = false;
1414 >    public static class TrackedLongRunnable implements Runnable {
1415 >        public volatile boolean done = false;
1416 >        public void run() {
1417 >            try {
1418 >                delay(LONG_DELAY_MS);
1419 >                done = true;
1420 >            } catch (InterruptedException ok) {}
1421 >        }
1422 >    }
1423 >
1424 >    public static class TrackedNoOpRunnable implements Runnable {
1425 >        public volatile boolean done = false;
1426          public void run() {
1427              done = true;
1428          }
1429      }
1430  
1431 <    static class TrackedCallable implements Callable {
1432 <        volatile boolean done = false;
1431 >    public static class TrackedCallable implements Callable {
1432 >        public volatile boolean done = false;
1433          public Object call() {
1434              try {
1435 <                Thread.sleep(SMALL_DELAY_MS);
1435 >                delay(SMALL_DELAY_MS);
1436                  done = true;
1437 <            } catch(Exception e){
537 <            }
1437 >            } catch (InterruptedException ok) {}
1438              return Boolean.TRUE;
1439          }
1440      }
1441  
1442 +    /**
1443 +     * Analog of CheckedRunnable for RecursiveAction
1444 +     */
1445 +    public abstract class CheckedRecursiveAction extends RecursiveAction {
1446 +        protected abstract void realCompute() throws Throwable;
1447 +
1448 +        @Override protected final void compute() {
1449 +            try {
1450 +                realCompute();
1451 +            } catch (Throwable fail) {
1452 +                threadUnexpectedException(fail);
1453 +            }
1454 +        }
1455 +    }
1456 +
1457 +    /**
1458 +     * Analog of CheckedCallable for RecursiveTask
1459 +     */
1460 +    public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1461 +        protected abstract T realCompute() throws Throwable;
1462 +
1463 +        @Override protected final T compute() {
1464 +            try {
1465 +                return realCompute();
1466 +            } catch (Throwable fail) {
1467 +                threadUnexpectedException(fail);
1468 +                return null;
1469 +            }
1470 +        }
1471 +    }
1472  
1473      /**
1474       * For use as RejectedExecutionHandler in constructors
1475       */
1476 <    static class NoOpREHandler implements RejectedExecutionHandler{
1477 <        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor){}
1476 >    public static class NoOpREHandler implements RejectedExecutionHandler {
1477 >        public void rejectedExecution(Runnable r,
1478 >                                      ThreadPoolExecutor executor) {}
1479 >    }
1480 >
1481 >    /**
1482 >     * A CyclicBarrier that uses timed await and fails with
1483 >     * AssertionFailedErrors instead of throwing checked exceptions.
1484 >     */
1485 >    public class CheckedBarrier extends CyclicBarrier {
1486 >        public CheckedBarrier(int parties) { super(parties); }
1487 >
1488 >        public int await() {
1489 >            try {
1490 >                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1491 >            } catch (TimeoutException timedOut) {
1492 >                throw new AssertionFailedError("timed out");
1493 >            } catch (Exception fail) {
1494 >                AssertionFailedError afe =
1495 >                    new AssertionFailedError("Unexpected exception: " + fail);
1496 >                afe.initCause(fail);
1497 >                throw afe;
1498 >            }
1499 >        }
1500 >    }
1501 >
1502 >    void checkEmpty(BlockingQueue q) {
1503 >        try {
1504 >            assertTrue(q.isEmpty());
1505 >            assertEquals(0, q.size());
1506 >            assertNull(q.peek());
1507 >            assertNull(q.poll());
1508 >            assertNull(q.poll(0, MILLISECONDS));
1509 >            assertEquals(q.toString(), "[]");
1510 >            assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1511 >            assertFalse(q.iterator().hasNext());
1512 >            try {
1513 >                q.element();
1514 >                shouldThrow();
1515 >            } catch (NoSuchElementException success) {}
1516 >            try {
1517 >                q.iterator().next();
1518 >                shouldThrow();
1519 >            } catch (NoSuchElementException success) {}
1520 >            try {
1521 >                q.remove();
1522 >                shouldThrow();
1523 >            } catch (NoSuchElementException success) {}
1524 >        } catch (InterruptedException fail) { threadUnexpectedException(fail); }
1525 >    }
1526 >
1527 >    void assertSerialEquals(Object x, Object y) {
1528 >        assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1529 >    }
1530 >
1531 >    void assertNotSerialEquals(Object x, Object y) {
1532 >        assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1533 >    }
1534 >
1535 >    byte[] serialBytes(Object o) {
1536 >        try {
1537 >            ByteArrayOutputStream bos = new ByteArrayOutputStream();
1538 >            ObjectOutputStream oos = new ObjectOutputStream(bos);
1539 >            oos.writeObject(o);
1540 >            oos.flush();
1541 >            oos.close();
1542 >            return bos.toByteArray();
1543 >        } catch (Throwable fail) {
1544 >            threadUnexpectedException(fail);
1545 >            return new byte[0];
1546 >        }
1547 >    }
1548 >
1549 >    @SuppressWarnings("unchecked")
1550 >    <T> T serialClone(T o) {
1551 >        try {
1552 >            ObjectInputStream ois = new ObjectInputStream
1553 >                (new ByteArrayInputStream(serialBytes(o)));
1554 >            T clone = (T) ois.readObject();
1555 >            assertSame(o.getClass(), clone.getClass());
1556 >            return clone;
1557 >        } catch (Throwable fail) {
1558 >            threadUnexpectedException(fail);
1559 >            return null;
1560 >        }
1561 >    }
1562 >
1563 >    public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1564 >                             Runnable... throwingActions) {
1565 >        for (Runnable throwingAction : throwingActions) {
1566 >            boolean threw = false;
1567 >            try { throwingAction.run(); }
1568 >            catch (Throwable t) {
1569 >                threw = true;
1570 >                if (!expectedExceptionClass.isInstance(t)) {
1571 >                    AssertionFailedError afe =
1572 >                        new AssertionFailedError
1573 >                        ("Expected " + expectedExceptionClass.getName() +
1574 >                         ", got " + t.getClass().getName());
1575 >                    afe.initCause(t);
1576 >                    threadUnexpectedException(afe);
1577 >                }
1578 >            }
1579 >            if (!threw)
1580 >                shouldThrow(expectedExceptionClass.getName());
1581 >        }
1582 >    }
1583 >
1584 >    public void assertIteratorExhausted(Iterator<?> it) {
1585 >        try {
1586 >            it.next();
1587 >            shouldThrow();
1588 >        } catch (NoSuchElementException success) {}
1589 >        assertFalse(it.hasNext());
1590      }
549
550    
1591   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines