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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines