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.43 by jsr166, Sat Nov 21 10:25:05 2009 UTC vs.
Revision 1.154 by jsr166, Sat Oct 3 19:39:16 2015 UTC

# Line 1 | Line 1
1   /*
2   * Written by Doug Lea with assistance from members of JCP JSR-166
3   * Expert Group and released to the public domain, as explained at
4 < * http://creativecommons.org/licenses/publicdomain
4 > * http://creativecommons.org/publicdomain/zero/1.0/
5   * Other contributors include Andrew Wright, Jeffrey Hayes,
6   * Pat Fisher, Mike Judd.
7   */
8  
9 import junit.framework.*;
10 import java.util.*;
11 import java.util.concurrent.*;
9   import static java.util.concurrent.TimeUnit.MILLISECONDS;
10 < import java.io.*;
11 < import java.security.*;
10 > import static java.util.concurrent.TimeUnit.NANOSECONDS;
11 >
12 > import java.io.ByteArrayInputStream;
13 > import java.io.ByteArrayOutputStream;
14 > import java.io.ObjectInputStream;
15 > import java.io.ObjectOutputStream;
16 > import java.lang.management.ManagementFactory;
17 > import java.lang.management.ThreadInfo;
18 > import java.lang.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 >     * Returns a timeout in milliseconds to be used in tests that
494 >     * verify that operations block or time out.
495 >     */
496 >    long timeoutMillis() {
497 >        return SHORT_DELAY_MS / 4;
498 >    }
499 >
500 >    /**
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 <     * Flag set true if any threadAssert methods fail
510 >     * The first exception encountered if any threadAssertXXX method fails.
511       */
512 <    volatile boolean threadFailed;
512 >    private final AtomicReference<Throwable> threadFailure
513 >        = new AtomicReference<Throwable>(null);
514  
515      /**
516 <     * Initializes test to indicate that no thread assertions have failed
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 +        threadDump();
523 +        threadFailure.compareAndSet(null, t);
524 +    }
525 +
526      public void setUp() {
527          setDelays();
528 <        threadFailed = false;
528 >    }
529 >
530 >    void tearDownFail(String format, Object... args) {
531 >        String msg = toString() + ": " + String.format(format, args);
532 >        System.err.println(msg);
533 >        threadDump();
534 >        throw new AssertionFailedError(msg);
535      }
536  
537      /**
538 <     * Triggers test case failure if any thread assertions have failed
538 >     * Extra checks that get done for all test cases.
539 >     *
540 >     * Triggers test case failure if any thread assertions have failed,
541 >     * by rethrowing, in the test harness thread, any exception recorded
542 >     * earlier by threadRecordFailure.
543 >     *
544 >     * Triggers test case failure if interrupt status is set in the main thread.
545 >     */
546 >    public void tearDown() throws Exception {
547 >        Throwable t = threadFailure.getAndSet(null);
548 >        if (t != null) {
549 >            if (t instanceof Error)
550 >                throw (Error) t;
551 >            else if (t instanceof RuntimeException)
552 >                throw (RuntimeException) t;
553 >            else if (t instanceof Exception)
554 >                throw (Exception) t;
555 >            else {
556 >                AssertionFailedError afe =
557 >                    new AssertionFailedError(t.toString());
558 >                afe.initCause(t);
559 >                throw afe;
560 >            }
561 >        }
562 >
563 >        if (Thread.interrupted())
564 >            tearDownFail("interrupt status set in main thread");
565 >
566 >        checkForkJoinPoolThreadLeaks();
567 >    }
568 >
569 >    /**
570 >     * Finds missing try { ... } finally { joinPool(e); }
571       */
572 <    public void tearDown() {
573 <        assertFalse(threadFailed);
572 >    void checkForkJoinPoolThreadLeaks() throws InterruptedException {
573 >        Thread[] survivors = new Thread[7];
574 >        int count = Thread.enumerate(survivors);
575 >        for (int i = 0; i < count; i++) {
576 >            Thread thread = survivors[i];
577 >            String name = thread.getName();
578 >            if (name.startsWith("ForkJoinPool-")) {
579 >                // give thread some time to terminate
580 >                thread.join(LONG_DELAY_MS);
581 >                if (thread.isAlive())
582 >                    tearDownFail("Found leaked ForkJoinPool thread thread=%s",
583 >                                 thread);
584 >            }
585 >        }
586 >
587 >        if (!ForkJoinPool.commonPool()
588 >            .awaitQuiescence(LONG_DELAY_MS, MILLISECONDS))
589 >            tearDownFail("ForkJoin common pool thread stuck");
590      }
591  
592      /**
593 <     * Fail, also setting status to indicate current testcase should fail
593 >     * Just like fail(reason), but additionally recording (using
594 >     * threadRecordFailure) any AssertionFailedError thrown, so that
595 >     * the current testcase will fail.
596       */
597      public void threadFail(String reason) {
598 <        threadFailed = true;
599 <        fail(reason);
598 >        try {
599 >            fail(reason);
600 >        } catch (AssertionFailedError t) {
601 >            threadRecordFailure(t);
602 >            throw t;
603 >        }
604      }
605  
606      /**
607 <     * If expression not true, set status to indicate current testcase
608 <     * should fail
607 >     * Just like assertTrue(b), but additionally recording (using
608 >     * threadRecordFailure) any AssertionFailedError thrown, so that
609 >     * the current testcase will fail.
610       */
611      public void threadAssertTrue(boolean b) {
612 <        if (!b) {
239 <            threadFailed = true;
612 >        try {
613              assertTrue(b);
614 +        } catch (AssertionFailedError t) {
615 +            threadRecordFailure(t);
616 +            throw t;
617          }
618      }
619  
620      /**
621 <     * If expression not false, set status to indicate current testcase
622 <     * should fail
621 >     * Just like assertFalse(b), but additionally recording (using
622 >     * threadRecordFailure) any AssertionFailedError thrown, so that
623 >     * the current testcase will fail.
624       */
625      public void threadAssertFalse(boolean b) {
626 <        if (b) {
250 <            threadFailed = true;
626 >        try {
627              assertFalse(b);
628 +        } catch (AssertionFailedError t) {
629 +            threadRecordFailure(t);
630 +            throw t;
631          }
632      }
633  
634      /**
635 <     * If argument not null, set status to indicate current testcase
636 <     * should fail
635 >     * Just like assertNull(x), but additionally recording (using
636 >     * threadRecordFailure) any AssertionFailedError thrown, so that
637 >     * the current testcase will fail.
638       */
639      public void threadAssertNull(Object x) {
640 <        if (x != null) {
261 <            threadFailed = true;
640 >        try {
641              assertNull(x);
642 +        } catch (AssertionFailedError t) {
643 +            threadRecordFailure(t);
644 +            throw t;
645          }
646      }
647  
648      /**
649 <     * If arguments not equal, set status to indicate current testcase
650 <     * should fail
649 >     * Just like assertEquals(x, y), but additionally recording (using
650 >     * threadRecordFailure) any AssertionFailedError thrown, so that
651 >     * the current testcase will fail.
652       */
653      public void threadAssertEquals(long x, long y) {
654 <        if (x != y) {
272 <            threadFailed = true;
654 >        try {
655              assertEquals(x, y);
656 +        } catch (AssertionFailedError t) {
657 +            threadRecordFailure(t);
658 +            throw t;
659          }
660      }
661  
662      /**
663 <     * If arguments not equal, set status to indicate current testcase
664 <     * should fail
663 >     * Just like assertEquals(x, y), but additionally recording (using
664 >     * threadRecordFailure) any AssertionFailedError thrown, so that
665 >     * the current testcase will fail.
666       */
667      public void threadAssertEquals(Object x, Object y) {
668 <        if (x != y && (x == null || !x.equals(y))) {
283 <            threadFailed = true;
668 >        try {
669              assertEquals(x, y);
670 +        } catch (AssertionFailedError fail) {
671 +            threadRecordFailure(fail);
672 +            throw fail;
673 +        } catch (Throwable fail) {
674 +            threadUnexpectedException(fail);
675          }
676      }
677  
678      /**
679 <     * threadFail with message "should throw exception"
679 >     * Just like assertSame(x, y), but additionally recording (using
680 >     * threadRecordFailure) any AssertionFailedError thrown, so that
681 >     * the current testcase will fail.
682 >     */
683 >    public void threadAssertSame(Object x, Object y) {
684 >        try {
685 >            assertSame(x, y);
686 >        } catch (AssertionFailedError fail) {
687 >            threadRecordFailure(fail);
688 >            throw fail;
689 >        }
690 >    }
691 >
692 >    /**
693 >     * Calls threadFail with message "should throw exception".
694       */
695      public void threadShouldThrow() {
696 <        threadFailed = true;
293 <        fail("should throw exception");
696 >        threadFail("should throw exception");
697      }
698  
699      /**
700 <     * threadFail with message "should throw" + exceptionName
700 >     * Calls threadFail with message "should throw" + exceptionName.
701       */
702      public void threadShouldThrow(String exceptionName) {
703 <        threadFailed = true;
704 <        fail("should throw " + exceptionName);
703 >        threadFail("should throw " + exceptionName);
704 >    }
705 >
706 >    /**
707 >     * Records the given exception using {@link #threadRecordFailure},
708 >     * then rethrows the exception, wrapping it in an
709 >     * AssertionFailedError if necessary.
710 >     */
711 >    public void threadUnexpectedException(Throwable t) {
712 >        threadRecordFailure(t);
713 >        t.printStackTrace();
714 >        if (t instanceof RuntimeException)
715 >            throw (RuntimeException) t;
716 >        else if (t instanceof Error)
717 >            throw (Error) t;
718 >        else {
719 >            AssertionFailedError afe =
720 >                new AssertionFailedError("unexpected exception: " + t);
721 >            afe.initCause(t);
722 >            throw afe;
723 >        }
724      }
725  
726      /**
727 <     * threadFail with message "Unexpected exception"
727 >     * Delays, via Thread.sleep, for the given millisecond delay, but
728 >     * if the sleep is shorter than specified, may re-sleep or yield
729 >     * until time elapses.
730       */
731 <    public void threadUnexpectedException() {
732 <        threadFailed = true;
733 <        fail("Unexpected exception");
731 >    static void delay(long millis) throws InterruptedException {
732 >        long startTime = System.nanoTime();
733 >        long ns = millis * 1000 * 1000;
734 >        for (;;) {
735 >            if (millis > 0L)
736 >                Thread.sleep(millis);
737 >            else // too short to sleep
738 >                Thread.yield();
739 >            long d = ns - (System.nanoTime() - startTime);
740 >            if (d > 0L)
741 >                millis = d / (1000 * 1000);
742 >            else
743 >                break;
744 >        }
745      }
746  
747      /**
748 <     * threadFail with message "Unexpected exception", with argument
748 >     * Allows use of try-with-resources with per-test thread pools.
749       */
750 <    public void threadUnexpectedException(Throwable ex) {
751 <        threadFailed = true;
752 <        ex.printStackTrace();
753 <        fail("Unexpected exception: " + ex);
750 >    static class PoolCloser<T extends ExecutorService>
751 >            implements AutoCloseable {
752 >        public final T pool;
753 >        public PoolCloser(T pool) { this.pool = pool; }
754 >        public void close() { joinPool(pool); }
755      }
756  
757      /**
758 <     * Wait out termination of a thread pool or fail doing so
758 >     * Waits out termination of a thread pool or fails doing so.
759       */
760 <    public void joinPool(ExecutorService exec) {
760 >    static void joinPool(ExecutorService pool) {
761          try {
762 <            exec.shutdown();
763 <            assertTrue(exec.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
762 >            pool.shutdown();
763 >            if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS))
764 >                fail("ExecutorService " + pool +
765 >                     " did not terminate in a timely manner");
766          } catch (SecurityException ok) {
767              // Allowed in case test doesn't have privs
768 <        } catch (InterruptedException ie) {
769 <            fail("Unexpected exception");
768 >        } catch (InterruptedException fail) {
769 >            fail("Unexpected InterruptedException");
770          }
771      }
772  
773 +    /** Like Runnable, but with the freedom to throw anything */
774 +    interface Action { public void run() throws Throwable; }
775  
776      /**
777 <     * fail with message "should throw exception"
777 >     * Runs all the given actions in parallel, failing if any fail.
778 >     * Useful for running multiple variants of tests that are
779 >     * necessarily individually slow because they must block.
780       */
781 <    public void shouldThrow() {
782 <        fail("Should throw exception");
781 >    void testInParallel(Action ... actions) {
782 >        try (PoolCloser<ExecutorService> poolCloser
783 >             = new PoolCloser<>(Executors.newCachedThreadPool())) {
784 >            ExecutorService pool = poolCloser.pool;
785 >            ArrayList<Future<?>> futures = new ArrayList<>(actions.length);
786 >            for (final Action action : actions)
787 >                futures.add(pool.submit(new CheckedRunnable() {
788 >                    public void realRun() throws Throwable { action.run();}}));
789 >            for (Future<?> future : futures)
790 >                try {
791 >                    assertNull(future.get(LONG_DELAY_MS, MILLISECONDS));
792 >                } catch (ExecutionException ex) {
793 >                    threadUnexpectedException(ex.getCause());
794 >                } catch (Exception ex) {
795 >                    threadUnexpectedException(ex);
796 >                }
797 >        }
798      }
799  
800      /**
801 <     * fail with message "should throw " + exceptionName
801 >     * A debugging tool to print all stack traces, as jstack does.
802 >     * Uninteresting threads are filtered out.
803       */
804 <    public void shouldThrow(String exceptionName) {
805 <        fail("Should throw " + exceptionName);
804 >    static void threadDump() {
805 >        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
806 >        System.err.println("------ stacktrace dump start ------");
807 >        for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) {
808 >            String name = info.getThreadName();
809 >            if ("Signal Dispatcher".equals(name))
810 >                continue;
811 >            if ("Reference Handler".equals(name)
812 >                && info.getLockName().startsWith("java.lang.ref.Reference$Lock"))
813 >                continue;
814 >            if ("Finalizer".equals(name)
815 >                && info.getLockName().startsWith("java.lang.ref.ReferenceQueue$Lock"))
816 >                continue;
817 >            System.err.print(info);
818 >        }
819 >        System.err.println("------ stacktrace dump end ------");
820      }
821  
822      /**
823 <     * fail with message "Unexpected exception"
823 >     * Checks that thread does not terminate within the default
824 >     * millisecond delay of {@code timeoutMillis()}.
825       */
826 <    public void unexpectedException() {
827 <        fail("Unexpected exception");
826 >    void assertThreadStaysAlive(Thread thread) {
827 >        assertThreadStaysAlive(thread, timeoutMillis());
828      }
829  
830      /**
831 <     * fail with message "Unexpected exception", with argument
831 >     * Checks that thread does not terminate within the given millisecond delay.
832       */
833 <    public void unexpectedException(Throwable ex) {
834 <        ex.printStackTrace();
835 <        fail("Unexpected exception: " + ex);
833 >    void assertThreadStaysAlive(Thread thread, long millis) {
834 >        try {
835 >            // No need to optimize the failing case via Thread.join.
836 >            delay(millis);
837 >            assertTrue(thread.isAlive());
838 >        } catch (InterruptedException fail) {
839 >            fail("Unexpected InterruptedException");
840 >        }
841      }
842  
843 +    /**
844 +     * Checks that the threads do not terminate within the default
845 +     * millisecond delay of {@code timeoutMillis()}.
846 +     */
847 +    void assertThreadsStayAlive(Thread... threads) {
848 +        assertThreadsStayAlive(timeoutMillis(), threads);
849 +    }
850 +
851 +    /**
852 +     * Checks that the threads do not terminate within the given millisecond delay.
853 +     */
854 +    void assertThreadsStayAlive(long millis, Thread... threads) {
855 +        try {
856 +            // No need to optimize the failing case via Thread.join.
857 +            delay(millis);
858 +            for (Thread thread : threads)
859 +                assertTrue(thread.isAlive());
860 +        } catch (InterruptedException fail) {
861 +            fail("Unexpected InterruptedException");
862 +        }
863 +    }
864 +
865 +    /**
866 +     * Checks that future.get times out, with the default timeout of
867 +     * {@code timeoutMillis()}.
868 +     */
869 +    void assertFutureTimesOut(Future future) {
870 +        assertFutureTimesOut(future, timeoutMillis());
871 +    }
872 +
873 +    /**
874 +     * Checks that future.get times out, with the given millisecond timeout.
875 +     */
876 +    void assertFutureTimesOut(Future future, long timeoutMillis) {
877 +        long startTime = System.nanoTime();
878 +        try {
879 +            future.get(timeoutMillis, MILLISECONDS);
880 +            shouldThrow();
881 +        } catch (TimeoutException success) {
882 +        } catch (Exception fail) {
883 +            threadUnexpectedException(fail);
884 +        } finally { future.cancel(true); }
885 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
886 +    }
887 +
888 +    /**
889 +     * Fails with message "should throw exception".
890 +     */
891 +    public void shouldThrow() {
892 +        fail("Should throw exception");
893 +    }
894 +
895 +    /**
896 +     * Fails with message "should throw " + exceptionName.
897 +     */
898 +    public void shouldThrow(String exceptionName) {
899 +        fail("Should throw " + exceptionName);
900 +    }
901  
902      /**
903       * The number of elements to place in collections, arrays, etc.
904       */
905 <    static final int SIZE = 20;
905 >    public static final int SIZE = 20;
906  
907      // Some convenient Integer constants
908  
909 <    static final Integer zero = new Integer(0);
910 <    static final Integer one = new Integer(1);
911 <    static final Integer two = new Integer(2);
912 <    static final Integer three  = new Integer(3);
913 <    static final Integer four  = new Integer(4);
914 <    static final Integer five  = new Integer(5);
915 <    static final Integer six = new Integer(6);
916 <    static final Integer seven = new Integer(7);
917 <    static final Integer eight = new Integer(8);
918 <    static final Integer nine = new Integer(9);
919 <    static final Integer m1  = new Integer(-1);
920 <    static final Integer m2  = new Integer(-2);
921 <    static final Integer m3  = new Integer(-3);
922 <    static final Integer m4 = new Integer(-4);
923 <    static final Integer m5 = new Integer(-5);
924 <    static final Integer m6 = new Integer(-6);
925 <    static final Integer m10 = new Integer(-10);
909 >    public static final Integer zero  = new Integer(0);
910 >    public static final Integer one   = new Integer(1);
911 >    public static final Integer two   = new Integer(2);
912 >    public static final Integer three = new Integer(3);
913 >    public static final Integer four  = new Integer(4);
914 >    public static final Integer five  = new Integer(5);
915 >    public static final Integer six   = new Integer(6);
916 >    public static final Integer seven = new Integer(7);
917 >    public static final Integer eight = new Integer(8);
918 >    public static final Integer nine  = new Integer(9);
919 >    public static final Integer m1  = new Integer(-1);
920 >    public static final Integer m2  = new Integer(-2);
921 >    public static final Integer m3  = new Integer(-3);
922 >    public static final Integer m4  = new Integer(-4);
923 >    public static final Integer m5  = new Integer(-5);
924 >    public static final Integer m6  = new Integer(-6);
925 >    public static final Integer m10 = new Integer(-10);
926 >
927 >    /**
928 >     * Runs Runnable r with a security policy that permits precisely
929 >     * the specified permissions.  If there is no current security
930 >     * manager, the runnable is run twice, both with and without a
931 >     * security manager.  We require that any security manager permit
932 >     * getPolicy/setPolicy.
933 >     */
934 >    public void runWithPermissions(Runnable r, Permission... permissions) {
935 >        SecurityManager sm = System.getSecurityManager();
936 >        if (sm == null) {
937 >            r.run();
938 >        }
939 >        runWithSecurityManagerWithPermissions(r, permissions);
940 >    }
941  
942 +    /**
943 +     * Runs Runnable r with a security policy that permits precisely
944 +     * the specified permissions.  If there is no current security
945 +     * manager, a temporary one is set for the duration of the
946 +     * Runnable.  We require that any security manager permit
947 +     * getPolicy/setPolicy.
948 +     */
949 +    public void runWithSecurityManagerWithPermissions(Runnable r,
950 +                                                      Permission... permissions) {
951 +        SecurityManager sm = System.getSecurityManager();
952 +        if (sm == null) {
953 +            Policy savedPolicy = Policy.getPolicy();
954 +            try {
955 +                Policy.setPolicy(permissivePolicy());
956 +                System.setSecurityManager(new SecurityManager());
957 +                runWithSecurityManagerWithPermissions(r, permissions);
958 +            } finally {
959 +                System.setSecurityManager(null);
960 +                Policy.setPolicy(savedPolicy);
961 +            }
962 +        } else {
963 +            Policy savedPolicy = Policy.getPolicy();
964 +            AdjustablePolicy policy = new AdjustablePolicy(permissions);
965 +            Policy.setPolicy(policy);
966 +
967 +            try {
968 +                r.run();
969 +            } finally {
970 +                policy.addPermission(new SecurityPermission("setPolicy"));
971 +                Policy.setPolicy(savedPolicy);
972 +            }
973 +        }
974 +    }
975 +
976 +    /**
977 +     * Runs a runnable without any permissions.
978 +     */
979 +    public void runWithoutPermissions(Runnable r) {
980 +        runWithPermissions(r);
981 +    }
982  
983      /**
984       * A security policy where new permissions can be dynamically added
985       * or all cleared.
986       */
987 <    static class AdjustablePolicy extends java.security.Policy {
987 >    public static class AdjustablePolicy extends java.security.Policy {
988          Permissions perms = new Permissions();
989 <        AdjustablePolicy() { }
989 >        AdjustablePolicy(Permission... permissions) {
990 >            for (Permission permission : permissions)
991 >                perms.add(permission);
992 >        }
993          void addPermission(Permission perm) { perms.add(perm); }
994          void clearPermissions() { perms = new Permissions(); }
995          public PermissionCollection getPermissions(CodeSource cs) {
# Line 408 | Line 1002 | public class JSR166TestCase extends Test
1002              return perms.implies(p);
1003          }
1004          public void refresh() {}
1005 +        public String toString() {
1006 +            List<Permission> ps = new ArrayList<Permission>();
1007 +            for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
1008 +                ps.add(e.nextElement());
1009 +            return "AdjustablePolicy with permissions " + ps;
1010 +        }
1011      }
1012  
1013      /**
1014 <     * Sleep until the timeout has elapsed, or interrupted.
415 <     * Does <em>NOT</em> throw InterruptedException.
1014 >     * Returns a policy containing all the permissions we ever need.
1015       */
1016 <    void sleepTillInterrupted(long timeoutMillis) {
1016 >    public static Policy permissivePolicy() {
1017 >        return new AdjustablePolicy
1018 >            // Permissions j.u.c. needs directly
1019 >            (new RuntimePermission("modifyThread"),
1020 >             new RuntimePermission("getClassLoader"),
1021 >             new RuntimePermission("setContextClassLoader"),
1022 >             // Permissions needed to change permissions!
1023 >             new SecurityPermission("getPolicy"),
1024 >             new SecurityPermission("setPolicy"),
1025 >             new RuntimePermission("setSecurityManager"),
1026 >             // Permissions needed by the junit test harness
1027 >             new RuntimePermission("accessDeclaredMembers"),
1028 >             new PropertyPermission("*", "read"),
1029 >             new java.io.FilePermission("<<ALL FILES>>", "read"));
1030 >    }
1031 >
1032 >    /**
1033 >     * Sleeps until the given time has elapsed.
1034 >     * Throws AssertionFailedError if interrupted.
1035 >     */
1036 >    void sleep(long millis) {
1037          try {
1038 <            Thread.sleep(timeoutMillis);
1039 <        } catch (InterruptedException wakeup) {
1038 >            delay(millis);
1039 >        } catch (InterruptedException fail) {
1040 >            AssertionFailedError afe =
1041 >                new AssertionFailedError("Unexpected InterruptedException");
1042 >            afe.initCause(fail);
1043 >            throw afe;
1044 >        }
1045 >    }
1046 >
1047 >    /**
1048 >     * Spin-waits up to the specified number of milliseconds for the given
1049 >     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1050 >     */
1051 >    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
1052 >        long startTime = System.nanoTime();
1053 >        for (;;) {
1054 >            Thread.State s = thread.getState();
1055 >            if (s == Thread.State.BLOCKED ||
1056 >                s == Thread.State.WAITING ||
1057 >                s == Thread.State.TIMED_WAITING)
1058 >                return;
1059 >            else if (s == Thread.State.TERMINATED)
1060 >                fail("Unexpected thread termination");
1061 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
1062 >                threadAssertTrue(thread.isAlive());
1063 >                return;
1064 >            }
1065 >            Thread.yield();
1066          }
1067      }
1068  
1069      /**
1070 <     * Returns a new started Thread running the given runnable.
1070 >     * Waits up to LONG_DELAY_MS for the given thread to enter a wait
1071 >     * state: BLOCKED, WAITING, or TIMED_WAITING.
1072 >     */
1073 >    void waitForThreadToEnterWaitState(Thread thread) {
1074 >        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
1075 >    }
1076 >
1077 >    /**
1078 >     * Returns the number of milliseconds since time given by
1079 >     * startNanoTime, which must have been previously returned from a
1080 >     * call to {@link System#nanoTime()}.
1081 >     */
1082 >    static long millisElapsedSince(long startNanoTime) {
1083 >        return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
1084 >    }
1085 >
1086 > //     void assertTerminatesPromptly(long timeoutMillis, Runnable r) {
1087 > //         long startTime = System.nanoTime();
1088 > //         try {
1089 > //             r.run();
1090 > //         } catch (Throwable fail) { threadUnexpectedException(fail); }
1091 > //         if (millisElapsedSince(startTime) > timeoutMillis/2)
1092 > //             throw new AssertionFailedError("did not return promptly");
1093 > //     }
1094 >
1095 > //     void assertTerminatesPromptly(Runnable r) {
1096 > //         assertTerminatesPromptly(LONG_DELAY_MS/2, r);
1097 > //     }
1098 >
1099 >    /**
1100 >     * Checks that timed f.get() returns the expected value, and does not
1101 >     * wait for the timeout to elapse before returning.
1102 >     */
1103 >    <T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) {
1104 >        long startTime = System.nanoTime();
1105 >        try {
1106 >            assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
1107 >        } catch (Throwable fail) { threadUnexpectedException(fail); }
1108 >        if (millisElapsedSince(startTime) > timeoutMillis/2)
1109 >            throw new AssertionFailedError("timed get did not return promptly");
1110 >    }
1111 >
1112 >    <T> void checkTimedGet(Future<T> f, T expectedValue) {
1113 >        checkTimedGet(f, expectedValue, LONG_DELAY_MS);
1114 >    }
1115 >
1116 >    /**
1117 >     * Returns a new started daemon Thread running the given runnable.
1118       */
1119      Thread newStartedThread(Runnable runnable) {
1120          Thread t = new Thread(runnable);
1121 +        t.setDaemon(true);
1122          t.start();
1123          return t;
1124      }
1125  
1126 +    /**
1127 +     * Waits for the specified time (in milliseconds) for the thread
1128 +     * to terminate (using {@link Thread#join(long)}), else interrupts
1129 +     * the thread (in the hope that it may terminate later) and fails.
1130 +     */
1131 +    void awaitTermination(Thread t, long timeoutMillis) {
1132 +        try {
1133 +            t.join(timeoutMillis);
1134 +        } catch (InterruptedException fail) {
1135 +            threadUnexpectedException(fail);
1136 +        } finally {
1137 +            if (t.getState() != Thread.State.TERMINATED) {
1138 +                t.interrupt();
1139 +                fail("Test timed out");
1140 +            }
1141 +        }
1142 +    }
1143 +
1144 +    /**
1145 +     * Waits for LONG_DELAY_MS milliseconds for the thread to
1146 +     * terminate (using {@link Thread#join(long)}), else interrupts
1147 +     * the thread (in the hope that it may terminate later) and fails.
1148 +     */
1149 +    void awaitTermination(Thread t) {
1150 +        awaitTermination(t, LONG_DELAY_MS);
1151 +    }
1152 +
1153      // Some convenient Runnable classes
1154  
1155 <    abstract class CheckedRunnable implements Runnable {
1156 <        abstract void realRun() throws Throwable;
1155 >    public abstract class CheckedRunnable implements Runnable {
1156 >        protected abstract void realRun() throws Throwable;
1157  
1158          public final void run() {
1159              try {
1160                  realRun();
1161 <            } catch (Throwable t) {
1162 <                threadUnexpectedException(t);
1161 >            } catch (Throwable fail) {
1162 >                threadUnexpectedException(fail);
1163              }
1164          }
1165      }
1166  
1167 <    abstract class RunnableShouldThrow implements Runnable {
1168 <        abstract void realRun() throws Throwable;
1167 >    public abstract class RunnableShouldThrow implements Runnable {
1168 >        protected abstract void realRun() throws Throwable;
1169  
1170          final Class<?> exceptionClass;
1171  
# Line 457 | Line 1177 | public class JSR166TestCase extends Test
1177              try {
1178                  realRun();
1179                  threadShouldThrow(exceptionClass.getSimpleName());
460            } catch (InterruptedException success) {
1180              } catch (Throwable t) {
1181                  if (! exceptionClass.isInstance(t))
1182                      threadUnexpectedException(t);
# Line 465 | Line 1184 | public class JSR166TestCase extends Test
1184          }
1185      }
1186  
1187 <    abstract class ThreadShouldThrow extends Thread {
1188 <        abstract void realRun() throws Throwable;
1187 >    public abstract class ThreadShouldThrow extends Thread {
1188 >        protected abstract void realRun() throws Throwable;
1189  
1190          final Class<?> exceptionClass;
1191  
# Line 478 | Line 1197 | public class JSR166TestCase extends Test
1197              try {
1198                  realRun();
1199                  threadShouldThrow(exceptionClass.getSimpleName());
481            } catch (InterruptedException success) {
1200              } catch (Throwable t) {
1201                  if (! exceptionClass.isInstance(t))
1202                      threadUnexpectedException(t);
# Line 486 | Line 1204 | public class JSR166TestCase extends Test
1204          }
1205      }
1206  
1207 <    abstract class CheckedInterruptedRunnable implements Runnable {
1208 <        abstract void realRun() throws Throwable;
1207 >    public abstract class CheckedInterruptedRunnable implements Runnable {
1208 >        protected abstract void realRun() throws Throwable;
1209  
1210          public final void run() {
1211              try {
1212                  realRun();
1213                  threadShouldThrow("InterruptedException");
1214              } catch (InterruptedException success) {
1215 <            } catch (Throwable t) {
1216 <                threadUnexpectedException(t);
1215 >                threadAssertFalse(Thread.interrupted());
1216 >            } catch (Throwable fail) {
1217 >                threadUnexpectedException(fail);
1218              }
1219          }
1220      }
1221  
1222 <    abstract class CheckedCallable<T> implements Callable<T> {
1223 <        abstract T realCall() throws Throwable;
1222 >    public abstract class CheckedCallable<T> implements Callable<T> {
1223 >        protected abstract T realCall() throws Throwable;
1224  
1225          public final T call() {
1226              try {
1227                  return realCall();
1228 <            } catch (Throwable t) {
1229 <                threadUnexpectedException(t);
1228 >            } catch (Throwable fail) {
1229 >                threadUnexpectedException(fail);
1230 >                return null;
1231              }
512            return null;
1232          }
1233      }
1234  
1235 <    abstract class CheckedInterruptedCallable<T> implements Callable<T> {
1236 <        abstract T realCall() throws Throwable;
1235 >    public abstract class CheckedInterruptedCallable<T>
1236 >        implements Callable<T> {
1237 >        protected abstract T realCall() throws Throwable;
1238  
1239          public final T call() {
1240              try {
# Line 522 | Line 1242 | public class JSR166TestCase extends Test
1242                  threadShouldThrow("InterruptedException");
1243                  return result;
1244              } catch (InterruptedException success) {
1245 <            } catch (Throwable t) {
1246 <                threadUnexpectedException(t);
1245 >                threadAssertFalse(Thread.interrupted());
1246 >            } catch (Throwable fail) {
1247 >                threadUnexpectedException(fail);
1248              }
1249              return null;
1250          }
1251      }
1252  
1253 <    static class NoOpRunnable implements Runnable {
1253 >    public static class NoOpRunnable implements Runnable {
1254          public void run() {}
1255      }
1256  
1257 <    static class NoOpCallable implements Callable {
1257 >    public static class NoOpCallable implements Callable {
1258          public Object call() { return Boolean.TRUE; }
1259      }
1260  
1261 <    static final String TEST_STRING = "a test string";
1261 >    public static final String TEST_STRING = "a test string";
1262 >
1263 >    public static class StringTask implements Callable<String> {
1264 >        final String value;
1265 >        public StringTask() { this(TEST_STRING); }
1266 >        public StringTask(String value) { this.value = value; }
1267 >        public String call() { return value; }
1268 >    }
1269 >
1270 >    public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
1271 >        return new CheckedCallable<String>() {
1272 >            protected String realCall() {
1273 >                try {
1274 >                    latch.await();
1275 >                } catch (InterruptedException quittingTime) {}
1276 >                return TEST_STRING;
1277 >            }};
1278 >    }
1279  
1280 <    static class StringTask implements Callable<String> {
1281 <        public String call() { return TEST_STRING; }
1280 >    public Runnable countDowner(final CountDownLatch latch) {
1281 >        return new CheckedRunnable() {
1282 >            public void realRun() throws InterruptedException {
1283 >                latch.countDown();
1284 >            }};
1285      }
1286  
1287 <    static class NPETask implements Callable<String> {
1287 >    public Runnable awaiter(final CountDownLatch latch) {
1288 >        return new CheckedRunnable() {
1289 >            public void realRun() throws InterruptedException {
1290 >                await(latch);
1291 >            }};
1292 >    }
1293 >
1294 >    public void await(CountDownLatch latch) {
1295 >        try {
1296 >            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1297 >        } catch (Throwable fail) {
1298 >            threadUnexpectedException(fail);
1299 >        }
1300 >    }
1301 >
1302 >    public void await(Semaphore semaphore) {
1303 >        try {
1304 >            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1305 >        } catch (Throwable fail) {
1306 >            threadUnexpectedException(fail);
1307 >        }
1308 >    }
1309 >
1310 > //     /**
1311 > //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1312 > //      */
1313 > //     public void await(AtomicBoolean flag) {
1314 > //         await(flag, LONG_DELAY_MS);
1315 > //     }
1316 >
1317 > //     /**
1318 > //      * Spin-waits up to the specified timeout until flag becomes true.
1319 > //      */
1320 > //     public void await(AtomicBoolean flag, long timeoutMillis) {
1321 > //         long startTime = System.nanoTime();
1322 > //         while (!flag.get()) {
1323 > //             if (millisElapsedSince(startTime) > timeoutMillis)
1324 > //                 throw new AssertionFailedError("timed out");
1325 > //             Thread.yield();
1326 > //         }
1327 > //     }
1328 >
1329 >    public static class NPETask implements Callable<String> {
1330          public String call() { throw new NullPointerException(); }
1331      }
1332  
1333 <    static class CallableOne implements Callable<Integer> {
1333 >    public static class CallableOne implements Callable<Integer> {
1334          public Integer call() { return one; }
1335      }
1336  
1337 <    class ShortRunnable extends CheckedRunnable {
1338 <        void realRun() throws Throwable {
1339 <            Thread.sleep(SHORT_DELAY_MS);
1337 >    public class ShortRunnable extends CheckedRunnable {
1338 >        protected void realRun() throws Throwable {
1339 >            delay(SHORT_DELAY_MS);
1340          }
1341      }
1342  
1343 <    class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1344 <        void realRun() throws InterruptedException {
1345 <            Thread.sleep(SHORT_DELAY_MS);
1343 >    public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1344 >        protected void realRun() throws InterruptedException {
1345 >            delay(SHORT_DELAY_MS);
1346          }
1347      }
1348  
1349 <    class SmallRunnable extends CheckedRunnable {
1350 <        void realRun() throws Throwable {
1351 <            Thread.sleep(SMALL_DELAY_MS);
1349 >    public class SmallRunnable extends CheckedRunnable {
1350 >        protected void realRun() throws Throwable {
1351 >            delay(SMALL_DELAY_MS);
1352          }
1353      }
1354  
1355 <    class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1356 <        void realRun() {
1355 >    public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1356 >        protected void realRun() {
1357              try {
1358 <                Thread.sleep(SMALL_DELAY_MS);
1359 <            }
577 <            catch (InterruptedException ok) {
578 <            }
1358 >                delay(SMALL_DELAY_MS);
1359 >            } catch (InterruptedException ok) {}
1360          }
1361      }
1362  
1363 <    class SmallCallable extends CheckedCallable {
1364 <        Object realCall() throws Throwable {
1365 <            Thread.sleep(SMALL_DELAY_MS);
1363 >    public class SmallCallable extends CheckedCallable {
1364 >        protected Object realCall() throws InterruptedException {
1365 >            delay(SMALL_DELAY_MS);
1366              return Boolean.TRUE;
1367          }
1368      }
1369  
1370 <    class SmallInterruptedRunnable extends CheckedInterruptedRunnable {
1371 <        void realRun() throws InterruptedException {
1372 <            Thread.sleep(SMALL_DELAY_MS);
1370 >    public class MediumRunnable extends CheckedRunnable {
1371 >        protected void realRun() throws Throwable {
1372 >            delay(MEDIUM_DELAY_MS);
1373          }
1374      }
1375  
1376 <    class MediumRunnable extends CheckedRunnable {
1377 <        void realRun() throws Throwable {
1378 <            Thread.sleep(MEDIUM_DELAY_MS);
1376 >    public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1377 >        protected void realRun() throws InterruptedException {
1378 >            delay(MEDIUM_DELAY_MS);
1379          }
1380      }
1381  
1382 <    class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1383 <        void realRun() throws InterruptedException {
1384 <            Thread.sleep(MEDIUM_DELAY_MS);
1385 <        }
1382 >    public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1383 >        return new CheckedRunnable() {
1384 >            protected void realRun() {
1385 >                try {
1386 >                    delay(timeoutMillis);
1387 >                } catch (InterruptedException ok) {}
1388 >            }};
1389      }
1390  
1391 <    class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1392 <        void realRun() {
1391 >    public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1392 >        protected void realRun() {
1393              try {
1394 <                Thread.sleep(MEDIUM_DELAY_MS);
1395 <            }
612 <            catch (InterruptedException ok) {
613 <            }
1394 >                delay(MEDIUM_DELAY_MS);
1395 >            } catch (InterruptedException ok) {}
1396          }
1397      }
1398  
1399 <    class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1400 <        void realRun() {
1399 >    public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1400 >        protected void realRun() {
1401              try {
1402 <                Thread.sleep(LONG_DELAY_MS);
1403 <            }
622 <            catch (InterruptedException ok) {
623 <            }
1402 >                delay(LONG_DELAY_MS);
1403 >            } catch (InterruptedException ok) {}
1404          }
1405      }
1406  
1407      /**
1408       * For use as ThreadFactory in constructors
1409       */
1410 <    static class SimpleThreadFactory implements ThreadFactory {
1410 >    public static class SimpleThreadFactory implements ThreadFactory {
1411          public Thread newThread(Runnable r) {
1412              return new Thread(r);
1413          }
1414      }
1415  
1416 <    static class TrackedShortRunnable implements Runnable {
1417 <        volatile boolean done = false;
1416 >    public interface TrackedRunnable extends Runnable {
1417 >        boolean isDone();
1418 >    }
1419 >
1420 >    public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
1421 >        return new TrackedRunnable() {
1422 >                private volatile boolean done = false;
1423 >                public boolean isDone() { return done; }
1424 >                public void run() {
1425 >                    try {
1426 >                        delay(timeoutMillis);
1427 >                        done = true;
1428 >                    } catch (InterruptedException ok) {}
1429 >                }
1430 >            };
1431 >    }
1432 >
1433 >    public static class TrackedShortRunnable implements Runnable {
1434 >        public volatile boolean done = false;
1435          public void run() {
1436              try {
1437 <                Thread.sleep(SMALL_DELAY_MS);
1437 >                delay(SHORT_DELAY_MS);
1438                  done = true;
1439 <            } catch (InterruptedException ok) {
643 <            }
1439 >            } catch (InterruptedException ok) {}
1440          }
1441      }
1442  
1443 <    static class TrackedMediumRunnable implements Runnable {
1444 <        volatile boolean done = false;
1443 >    public static class TrackedSmallRunnable implements Runnable {
1444 >        public volatile boolean done = false;
1445          public void run() {
1446              try {
1447 <                Thread.sleep(MEDIUM_DELAY_MS);
1447 >                delay(SMALL_DELAY_MS);
1448                  done = true;
1449 <            } catch (InterruptedException ok) {
654 <            }
1449 >            } catch (InterruptedException ok) {}
1450          }
1451      }
1452  
1453 <    static class TrackedLongRunnable implements Runnable {
1454 <        volatile boolean done = false;
1453 >    public static class TrackedMediumRunnable implements Runnable {
1454 >        public volatile boolean done = false;
1455          public void run() {
1456              try {
1457 <                Thread.sleep(LONG_DELAY_MS);
1457 >                delay(MEDIUM_DELAY_MS);
1458                  done = true;
1459 <            } catch (InterruptedException ok) {
665 <            }
1459 >            } catch (InterruptedException ok) {}
1460          }
1461      }
1462  
1463 <    static class TrackedNoOpRunnable implements Runnable {
1464 <        volatile boolean done = false;
1463 >    public static class TrackedLongRunnable implements Runnable {
1464 >        public volatile boolean done = false;
1465 >        public void run() {
1466 >            try {
1467 >                delay(LONG_DELAY_MS);
1468 >                done = true;
1469 >            } catch (InterruptedException ok) {}
1470 >        }
1471 >    }
1472 >
1473 >    public static class TrackedNoOpRunnable implements Runnable {
1474 >        public volatile boolean done = false;
1475          public void run() {
1476              done = true;
1477          }
1478      }
1479  
1480 <    static class TrackedCallable implements Callable {
1481 <        volatile boolean done = false;
1480 >    public static class TrackedCallable implements Callable {
1481 >        public volatile boolean done = false;
1482          public Object call() {
1483              try {
1484 <                Thread.sleep(SMALL_DELAY_MS);
1484 >                delay(SMALL_DELAY_MS);
1485                  done = true;
1486 <            } catch (InterruptedException ok) {
683 <            }
1486 >            } catch (InterruptedException ok) {}
1487              return Boolean.TRUE;
1488          }
1489      }
1490  
1491 +    /**
1492 +     * Analog of CheckedRunnable for RecursiveAction
1493 +     */
1494 +    public abstract class CheckedRecursiveAction extends RecursiveAction {
1495 +        protected abstract void realCompute() throws Throwable;
1496 +
1497 +        @Override protected final void compute() {
1498 +            try {
1499 +                realCompute();
1500 +            } catch (Throwable fail) {
1501 +                threadUnexpectedException(fail);
1502 +            }
1503 +        }
1504 +    }
1505 +
1506 +    /**
1507 +     * Analog of CheckedCallable for RecursiveTask
1508 +     */
1509 +    public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1510 +        protected abstract T realCompute() throws Throwable;
1511 +
1512 +        @Override protected final T compute() {
1513 +            try {
1514 +                return realCompute();
1515 +            } catch (Throwable fail) {
1516 +                threadUnexpectedException(fail);
1517 +                return null;
1518 +            }
1519 +        }
1520 +    }
1521  
1522      /**
1523       * For use as RejectedExecutionHandler in constructors
1524       */
1525 <    static class NoOpREHandler implements RejectedExecutionHandler {
1525 >    public static class NoOpREHandler implements RejectedExecutionHandler {
1526          public void rejectedExecution(Runnable r,
1527                                        ThreadPoolExecutor executor) {}
1528      }
1529  
1530 +    /**
1531 +     * A CyclicBarrier that uses timed await and fails with
1532 +     * AssertionFailedErrors instead of throwing checked exceptions.
1533 +     */
1534 +    public class CheckedBarrier extends CyclicBarrier {
1535 +        public CheckedBarrier(int parties) { super(parties); }
1536 +
1537 +        public int await() {
1538 +            try {
1539 +                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1540 +            } catch (TimeoutException timedOut) {
1541 +                throw new AssertionFailedError("timed out");
1542 +            } catch (Exception fail) {
1543 +                AssertionFailedError afe =
1544 +                    new AssertionFailedError("Unexpected exception: " + fail);
1545 +                afe.initCause(fail);
1546 +                throw afe;
1547 +            }
1548 +        }
1549 +    }
1550 +
1551 +    void checkEmpty(BlockingQueue q) {
1552 +        try {
1553 +            assertTrue(q.isEmpty());
1554 +            assertEquals(0, q.size());
1555 +            assertNull(q.peek());
1556 +            assertNull(q.poll());
1557 +            assertNull(q.poll(0, MILLISECONDS));
1558 +            assertEquals(q.toString(), "[]");
1559 +            assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1560 +            assertFalse(q.iterator().hasNext());
1561 +            try {
1562 +                q.element();
1563 +                shouldThrow();
1564 +            } catch (NoSuchElementException success) {}
1565 +            try {
1566 +                q.iterator().next();
1567 +                shouldThrow();
1568 +            } catch (NoSuchElementException success) {}
1569 +            try {
1570 +                q.remove();
1571 +                shouldThrow();
1572 +            } catch (NoSuchElementException success) {}
1573 +        } catch (InterruptedException fail) { threadUnexpectedException(fail); }
1574 +    }
1575 +
1576 +    void assertSerialEquals(Object x, Object y) {
1577 +        assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1578 +    }
1579 +
1580 +    void assertNotSerialEquals(Object x, Object y) {
1581 +        assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1582 +    }
1583 +
1584 +    byte[] serialBytes(Object o) {
1585 +        try {
1586 +            ByteArrayOutputStream bos = new ByteArrayOutputStream();
1587 +            ObjectOutputStream oos = new ObjectOutputStream(bos);
1588 +            oos.writeObject(o);
1589 +            oos.flush();
1590 +            oos.close();
1591 +            return bos.toByteArray();
1592 +        } catch (Throwable fail) {
1593 +            threadUnexpectedException(fail);
1594 +            return new byte[0];
1595 +        }
1596 +    }
1597 +
1598 +    @SuppressWarnings("unchecked")
1599 +    <T> T serialClone(T o) {
1600 +        try {
1601 +            ObjectInputStream ois = new ObjectInputStream
1602 +                (new ByteArrayInputStream(serialBytes(o)));
1603 +            T clone = (T) ois.readObject();
1604 +            assertSame(o.getClass(), clone.getClass());
1605 +            return clone;
1606 +        } catch (Throwable fail) {
1607 +            threadUnexpectedException(fail);
1608 +            return null;
1609 +        }
1610 +    }
1611 +
1612 +    public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1613 +                             Runnable... throwingActions) {
1614 +        for (Runnable throwingAction : throwingActions) {
1615 +            boolean threw = false;
1616 +            try { throwingAction.run(); }
1617 +            catch (Throwable t) {
1618 +                threw = true;
1619 +                if (!expectedExceptionClass.isInstance(t)) {
1620 +                    AssertionFailedError afe =
1621 +                        new AssertionFailedError
1622 +                        ("Expected " + expectedExceptionClass.getName() +
1623 +                         ", got " + t.getClass().getName());
1624 +                    afe.initCause(t);
1625 +                    threadUnexpectedException(afe);
1626 +                }
1627 +            }
1628 +            if (!threw)
1629 +                shouldThrow(expectedExceptionClass.getName());
1630 +        }
1631 +    }
1632 +
1633 +    public void assertIteratorExhausted(Iterator<?> it) {
1634 +        try {
1635 +            it.next();
1636 +            shouldThrow();
1637 +        } catch (NoSuchElementException success) {}
1638 +        assertFalse(it.hasNext());
1639 +    }
1640   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines