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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines