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.55 by jsr166, Mon Sep 20 20:42:37 2010 UTC vs.
Revision 1.126 by jsr166, Sat Jan 17 22:55:06 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.PropertyPermission;
11 import java.util.concurrent.*;
12 import java.util.concurrent.atomic.AtomicReference;
9   import static java.util.concurrent.TimeUnit.MILLISECONDS;
10 + import static java.util.concurrent.TimeUnit.NANOSECONDS;
11 +
12 + import java.io.ByteArrayInputStream;
13 + import java.io.ByteArrayOutputStream;
14 + import java.io.ObjectInputStream;
15 + import java.io.ObjectOutputStream;
16 + import java.lang.management.ManagementFactory;
17 + import java.lang.management.ThreadInfo;
18 + import java.lang.reflect.Method;
19   import java.security.CodeSource;
20   import java.security.Permission;
21   import java.security.PermissionCollection;
# Line 18 | Line 23 | import java.security.Permissions;
23   import java.security.Policy;
24   import java.security.ProtectionDomain;
25   import java.security.SecurityPermission;
26 + import java.util.ArrayList;
27 + import java.util.Arrays;
28 + import java.util.Date;
29 + import java.util.Enumeration;
30 + import java.util.Iterator;
31 + import java.util.List;
32 + import java.util.NoSuchElementException;
33 + import java.util.PropertyPermission;
34 + import java.util.concurrent.BlockingQueue;
35 + import java.util.concurrent.Callable;
36 + import java.util.concurrent.CountDownLatch;
37 + import java.util.concurrent.CyclicBarrier;
38 + import java.util.concurrent.ExecutorService;
39 + import java.util.concurrent.Future;
40 + import java.util.concurrent.RecursiveAction;
41 + import java.util.concurrent.RecursiveTask;
42 + import java.util.concurrent.RejectedExecutionHandler;
43 + import java.util.concurrent.Semaphore;
44 + import java.util.concurrent.ThreadFactory;
45 + import java.util.concurrent.ThreadPoolExecutor;
46 + import java.util.concurrent.TimeoutException;
47 + import java.util.concurrent.atomic.AtomicReference;
48 + import java.util.regex.Pattern;
49 +
50 + import junit.framework.AssertionFailedError;
51 + import junit.framework.Test;
52 + import junit.framework.TestCase;
53 + import junit.framework.TestSuite;
54  
55   /**
56   * Base class for JSR166 Junit TCK tests.  Defines some constants,
# Line 60 | Line 93 | import java.security.SecurityPermission;
93   *
94   * </ol>
95   *
96 < * <p> <b>Other notes</b>
96 > * <p><b>Other notes</b>
97   * <ul>
98   *
99   * <li> Usually, there is one testcase method per JSR166 method
# Line 96 | Line 129 | public class JSR166TestCase extends Test
129      private static final boolean useSecurityManager =
130          Boolean.getBoolean("jsr166.useSecurityManager");
131  
132 +    protected static final boolean expensiveTests =
133 +        Boolean.getBoolean("jsr166.expensiveTests");
134 +
135 +    /**
136 +     * If true, also run tests that are not part of the official tck
137 +     * because they test unspecified implementation details.
138 +     */
139 +    protected static final boolean testImplementationDetails =
140 +        Boolean.getBoolean("jsr166.testImplementationDetails");
141 +
142 +    /**
143 +     * If true, report on stdout all "slow" tests, that is, ones that
144 +     * take more than profileThreshold milliseconds to execute.
145 +     */
146 +    private static final boolean profileTests =
147 +        Boolean.getBoolean("jsr166.profileTests");
148 +
149 +    /**
150 +     * The number of milliseconds that tests are permitted for
151 +     * execution without being reported, when profileTests is set.
152 +     */
153 +    private static final long profileThreshold =
154 +        Long.getLong("jsr166.profileThreshold", 100);
155 +
156 +    /**
157 +     * The number of repetitions per test (for tickling rare bugs).
158 +     */
159 +    private static final int runsPerTest =
160 +        Integer.getInteger("jsr166.runsPerTest", 1);
161 +
162 +    /**
163 +     * A filter for tests to run, matching strings of the form
164 +     * methodName(className), e.g. "testInvokeAll5(ForkJoinPoolTest)"
165 +     * Usefully combined with jsr166.runsPerTest.
166 +     */
167 +    private static final Pattern methodFilter = methodFilter();
168 +
169 +    private static Pattern methodFilter() {
170 +        String regex = System.getProperty("jsr166.methodFilter");
171 +        return (regex == null) ? null : Pattern.compile(regex);
172 +    }
173 +
174 +    protected void runTest() throws Throwable {
175 +        if (methodFilter == null
176 +            || methodFilter.matcher(toString()).find()) {
177 +            for (int i = 0; i < runsPerTest; i++) {
178 +                if (profileTests)
179 +                    runTestProfiled();
180 +                else
181 +                    super.runTest();
182 +            }
183 +        }
184 +    }
185 +
186 +    protected void runTestProfiled() throws Throwable {
187 +        // Warmup run, notably to trigger all needed classloading.
188 +        super.runTest();
189 +        long t0 = System.nanoTime();
190 +        try {
191 +            super.runTest();
192 +        } finally {
193 +            long elapsedMillis = millisElapsedSince(t0);
194 +            if (elapsedMillis >= profileThreshold)
195 +                System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
196 +        }
197 +    }
198 +
199      /**
200 <     * Runs all JSR166 unit tests using junit.textui.TestRunner
200 >     * Runs all JSR166 unit tests using junit.textui.TestRunner.
201 >     * Optional command line arg provides the number of iterations to
202 >     * repeat running the tests.
203       */
204      public static void main(String[] args) {
205          if (useSecurityManager) {
# Line 105 | Line 207 | public class JSR166TestCase extends Test
207              Policy.setPolicy(permissivePolicy());
208              System.setSecurityManager(new SecurityManager());
209          }
210 <        int iters = 1;
211 <        if (args.length > 0)
110 <            iters = Integer.parseInt(args[0]);
210 >        int iters = (args.length == 0) ? 1 : Integer.parseInt(args[0]);
211 >
212          Test s = suite();
213          for (int i = 0; i < iters; ++i) {
214              junit.textui.TestRunner.run(s);
# Line 117 | Line 218 | public class JSR166TestCase extends Test
218          System.exit(0);
219      }
220  
221 +    public static TestSuite newTestSuite(Object... suiteOrClasses) {
222 +        TestSuite suite = new TestSuite();
223 +        for (Object suiteOrClass : suiteOrClasses) {
224 +            if (suiteOrClass instanceof TestSuite)
225 +                suite.addTest((TestSuite) suiteOrClass);
226 +            else if (suiteOrClass instanceof Class)
227 +                suite.addTest(new TestSuite((Class<?>) suiteOrClass));
228 +            else
229 +                throw new ClassCastException("not a test suite or class");
230 +        }
231 +        return suite;
232 +    }
233 +
234 +    public static void addNamedTestClasses(TestSuite suite,
235 +                                           String... testClassNames) {
236 +        for (String testClassName : testClassNames) {
237 +            try {
238 +                Class<?> testClass = Class.forName(testClassName);
239 +                Method m = testClass.getDeclaredMethod("suite",
240 +                                                       new Class<?>[0]);
241 +                suite.addTest(newTestSuite((Test)m.invoke(null)));
242 +            } catch (Exception e) {
243 +                throw new Error("Missing test class", e);
244 +            }
245 +        }
246 +    }
247 +
248 +    public static final double JAVA_CLASS_VERSION;
249 +    public static final String JAVA_SPECIFICATION_VERSION;
250 +    static {
251 +        try {
252 +            JAVA_CLASS_VERSION = java.security.AccessController.doPrivileged(
253 +                new java.security.PrivilegedAction<Double>() {
254 +                public Double run() {
255 +                    return Double.valueOf(System.getProperty("java.class.version"));}});
256 +            JAVA_SPECIFICATION_VERSION = java.security.AccessController.doPrivileged(
257 +                new java.security.PrivilegedAction<String>() {
258 +                public String run() {
259 +                    return System.getProperty("java.specification.version");}});
260 +        } catch (Throwable t) {
261 +            throw new Error(t);
262 +        }
263 +    }
264 +
265 +    public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
266 +    public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
267 +    public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
268 +    public static boolean atLeastJava9() {
269 +        // As of 2014-05, java9 still uses 52.0 class file version
270 +        return JAVA_SPECIFICATION_VERSION.startsWith("1.9");
271 +    }
272 +
273      /**
274 <     * Collects all JSR166 unit tests as one suite
274 >     * Collects all JSR166 unit tests as one suite.
275       */
276      public static Test suite() {
277 <        TestSuite suite = new TestSuite("JSR166 Unit Tests");
278 <
279 <        suite.addTest(new TestSuite(ForkJoinPoolTest.class));
280 <        suite.addTest(new TestSuite(ForkJoinTaskTest.class));
281 <        suite.addTest(new TestSuite(RecursiveActionTest.class));
282 <        suite.addTest(new TestSuite(RecursiveTaskTest.class));
283 <        suite.addTest(new TestSuite(LinkedTransferQueueTest.class));
284 <        suite.addTest(new TestSuite(PhaserTest.class));
285 <        suite.addTest(new TestSuite(ThreadLocalRandomTest.class));
286 <        suite.addTest(new TestSuite(AbstractExecutorServiceTest.class));
287 <        suite.addTest(new TestSuite(AbstractQueueTest.class));
288 <        suite.addTest(new TestSuite(AbstractQueuedSynchronizerTest.class));
289 <        suite.addTest(new TestSuite(AbstractQueuedLongSynchronizerTest.class));
290 <        suite.addTest(new TestSuite(ArrayBlockingQueueTest.class));
291 <        suite.addTest(new TestSuite(ArrayDequeTest.class));
292 <        suite.addTest(new TestSuite(AtomicBooleanTest.class));
293 <        suite.addTest(new TestSuite(AtomicIntegerArrayTest.class));
294 <        suite.addTest(new TestSuite(AtomicIntegerFieldUpdaterTest.class));
295 <        suite.addTest(new TestSuite(AtomicIntegerTest.class));
296 <        suite.addTest(new TestSuite(AtomicLongArrayTest.class));
297 <        suite.addTest(new TestSuite(AtomicLongFieldUpdaterTest.class));
298 <        suite.addTest(new TestSuite(AtomicLongTest.class));
299 <        suite.addTest(new TestSuite(AtomicMarkableReferenceTest.class));
300 <        suite.addTest(new TestSuite(AtomicReferenceArrayTest.class));
301 <        suite.addTest(new TestSuite(AtomicReferenceFieldUpdaterTest.class));
302 <        suite.addTest(new TestSuite(AtomicReferenceTest.class));
303 <        suite.addTest(new TestSuite(AtomicStampedReferenceTest.class));
304 <        suite.addTest(new TestSuite(ConcurrentHashMapTest.class));
305 <        suite.addTest(new TestSuite(ConcurrentLinkedDequeTest.class));
306 <        suite.addTest(new TestSuite(ConcurrentLinkedQueueTest.class));
307 <        suite.addTest(new TestSuite(ConcurrentSkipListMapTest.class));
308 <        suite.addTest(new TestSuite(ConcurrentSkipListSubMapTest.class));
309 <        suite.addTest(new TestSuite(ConcurrentSkipListSetTest.class));
310 <        suite.addTest(new TestSuite(ConcurrentSkipListSubSetTest.class));
311 <        suite.addTest(new TestSuite(CopyOnWriteArrayListTest.class));
312 <        suite.addTest(new TestSuite(CopyOnWriteArraySetTest.class));
313 <        suite.addTest(new TestSuite(CountDownLatchTest.class));
314 <        suite.addTest(new TestSuite(CyclicBarrierTest.class));
315 <        suite.addTest(new TestSuite(DelayQueueTest.class));
316 <        suite.addTest(new TestSuite(EntryTest.class));
317 <        suite.addTest(new TestSuite(ExchangerTest.class));
318 <        suite.addTest(new TestSuite(ExecutorsTest.class));
319 <        suite.addTest(new TestSuite(ExecutorCompletionServiceTest.class));
320 <        suite.addTest(new TestSuite(FutureTaskTest.class));
321 <        suite.addTest(new TestSuite(LinkedBlockingDequeTest.class));
322 <        suite.addTest(new TestSuite(LinkedBlockingQueueTest.class));
323 <        suite.addTest(new TestSuite(LinkedListTest.class));
324 <        suite.addTest(new TestSuite(LockSupportTest.class));
325 <        suite.addTest(new TestSuite(PriorityBlockingQueueTest.class));
326 <        suite.addTest(new TestSuite(PriorityQueueTest.class));
327 <        suite.addTest(new TestSuite(ReentrantLockTest.class));
328 <        suite.addTest(new TestSuite(ReentrantReadWriteLockTest.class));
329 <        suite.addTest(new TestSuite(ScheduledExecutorTest.class));
330 <        suite.addTest(new TestSuite(ScheduledExecutorSubclassTest.class));
331 <        suite.addTest(new TestSuite(SemaphoreTest.class));
332 <        suite.addTest(new TestSuite(SynchronousQueueTest.class));
333 <        suite.addTest(new TestSuite(SystemTest.class));
334 <        suite.addTest(new TestSuite(ThreadLocalTest.class));
335 <        suite.addTest(new TestSuite(ThreadPoolExecutorTest.class));
336 <        suite.addTest(new TestSuite(ThreadPoolExecutorSubclassTest.class));
337 <        suite.addTest(new TestSuite(ThreadTest.class));
338 <        suite.addTest(new TestSuite(TimeUnitTest.class));
339 <        suite.addTest(new TestSuite(TreeMapTest.class));
340 <        suite.addTest(new TestSuite(TreeSetTest.class));
341 <        suite.addTest(new TestSuite(TreeSubMapTest.class));
342 <        suite.addTest(new TestSuite(TreeSubSetTest.class));
277 >        // Java7+ test classes
278 >        TestSuite suite = newTestSuite(
279 >            ForkJoinPoolTest.suite(),
280 >            ForkJoinTaskTest.suite(),
281 >            RecursiveActionTest.suite(),
282 >            RecursiveTaskTest.suite(),
283 >            LinkedTransferQueueTest.suite(),
284 >            PhaserTest.suite(),
285 >            ThreadLocalRandomTest.suite(),
286 >            AbstractExecutorServiceTest.suite(),
287 >            AbstractQueueTest.suite(),
288 >            AbstractQueuedSynchronizerTest.suite(),
289 >            AbstractQueuedLongSynchronizerTest.suite(),
290 >            ArrayBlockingQueueTest.suite(),
291 >            ArrayDequeTest.suite(),
292 >            AtomicBooleanTest.suite(),
293 >            AtomicIntegerArrayTest.suite(),
294 >            AtomicIntegerFieldUpdaterTest.suite(),
295 >            AtomicIntegerTest.suite(),
296 >            AtomicLongArrayTest.suite(),
297 >            AtomicLongFieldUpdaterTest.suite(),
298 >            AtomicLongTest.suite(),
299 >            AtomicMarkableReferenceTest.suite(),
300 >            AtomicReferenceArrayTest.suite(),
301 >            AtomicReferenceFieldUpdaterTest.suite(),
302 >            AtomicReferenceTest.suite(),
303 >            AtomicStampedReferenceTest.suite(),
304 >            ConcurrentHashMapTest.suite(),
305 >            ConcurrentLinkedDequeTest.suite(),
306 >            ConcurrentLinkedQueueTest.suite(),
307 >            ConcurrentSkipListMapTest.suite(),
308 >            ConcurrentSkipListSubMapTest.suite(),
309 >            ConcurrentSkipListSetTest.suite(),
310 >            ConcurrentSkipListSubSetTest.suite(),
311 >            CopyOnWriteArrayListTest.suite(),
312 >            CopyOnWriteArraySetTest.suite(),
313 >            CountDownLatchTest.suite(),
314 >            CyclicBarrierTest.suite(),
315 >            DelayQueueTest.suite(),
316 >            EntryTest.suite(),
317 >            ExchangerTest.suite(),
318 >            ExecutorsTest.suite(),
319 >            ExecutorCompletionServiceTest.suite(),
320 >            FutureTaskTest.suite(),
321 >            LinkedBlockingDequeTest.suite(),
322 >            LinkedBlockingQueueTest.suite(),
323 >            LinkedListTest.suite(),
324 >            LockSupportTest.suite(),
325 >            PriorityBlockingQueueTest.suite(),
326 >            PriorityQueueTest.suite(),
327 >            ReentrantLockTest.suite(),
328 >            ReentrantReadWriteLockTest.suite(),
329 >            ScheduledExecutorTest.suite(),
330 >            ScheduledExecutorSubclassTest.suite(),
331 >            SemaphoreTest.suite(),
332 >            SynchronousQueueTest.suite(),
333 >            SystemTest.suite(),
334 >            ThreadLocalTest.suite(),
335 >            ThreadPoolExecutorTest.suite(),
336 >            ThreadPoolExecutorSubclassTest.suite(),
337 >            ThreadTest.suite(),
338 >            TimeUnitTest.suite(),
339 >            TreeMapTest.suite(),
340 >            TreeSetTest.suite(),
341 >            TreeSubMapTest.suite(),
342 >            TreeSubSetTest.suite());
343 >
344 >        // Java8+ test classes
345 >        if (atLeastJava8()) {
346 >            String[] java8TestClassNames = {
347 >                "Atomic8Test",
348 >                "CompletableFutureTest",
349 >                "ConcurrentHashMap8Test",
350 >                "CountedCompleterTest",
351 >                "DoubleAccumulatorTest",
352 >                "DoubleAdderTest",
353 >                "ForkJoinPool8Test",
354 >                "ForkJoinTask8Test",
355 >                "LongAccumulatorTest",
356 >                "LongAdderTest",
357 >                "SplittableRandomTest",
358 >                "StampedLockTest",
359 >                "ThreadLocalRandom8Test",
360 >            };
361 >            addNamedTestClasses(suite, java8TestClassNames);
362 >        }
363 >
364 >        // Java9+ test classes
365 >        if (atLeastJava9()) {
366 >            String[] java9TestClassNames = {
367 >                "ThreadPoolExecutor9Test",
368 >            };
369 >            addNamedTestClasses(suite, java9TestClassNames);
370 >        }
371  
372          return suite;
373      }
374  
375 +    // Delays for timing-dependent tests, in milliseconds.
376  
377      public static long SHORT_DELAY_MS;
378      public static long SMALL_DELAY_MS;
379      public static long MEDIUM_DELAY_MS;
380      public static long LONG_DELAY_MS;
381  
200
382      /**
383       * Returns the shortest timed delay. This could
384       * be reimplemented to use for example a Property.
# Line 206 | Line 387 | public class JSR166TestCase extends Test
387          return 50;
388      }
389  
209
390      /**
391       * Sets delays as multiples of SHORT_DELAY.
392       */
# Line 214 | Line 394 | public class JSR166TestCase extends Test
394          SHORT_DELAY_MS = getShortDelay();
395          SMALL_DELAY_MS  = SHORT_DELAY_MS * 5;
396          MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
397 <        LONG_DELAY_MS   = SHORT_DELAY_MS * 50;
397 >        LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
398 >    }
399 >
400 >    /**
401 >     * Returns a timeout in milliseconds to be used in tests that
402 >     * verify that operations block or time out.
403 >     */
404 >    long timeoutMillis() {
405 >        return SHORT_DELAY_MS / 4;
406 >    }
407 >
408 >    /**
409 >     * Returns a new Date instance representing a time delayMillis
410 >     * milliseconds in the future.
411 >     */
412 >    Date delayedDate(long delayMillis) {
413 >        return new Date(System.currentTimeMillis() + delayMillis);
414      }
415  
416      /**
# Line 238 | Line 434 | public class JSR166TestCase extends Test
434      }
435  
436      /**
437 +     * Extra checks that get done for all test cases.
438 +     *
439       * Triggers test case failure if any thread assertions have failed,
440       * by rethrowing, in the test harness thread, any exception recorded
441       * earlier by threadRecordFailure.
442 +     *
443 +     * Triggers test case failure if interrupt status is set in the main thread.
444       */
445      public void tearDown() throws Exception {
446 <        Throwable t = threadFailure.get();
446 >        Throwable t = threadFailure.getAndSet(null);
447          if (t != null) {
448              if (t instanceof Error)
449                  throw (Error) t;
# Line 251 | Line 451 | public class JSR166TestCase extends Test
451                  throw (RuntimeException) t;
452              else if (t instanceof Exception)
453                  throw (Exception) t;
454 <            else
455 <                throw new AssertionError(t);
454 >            else {
455 >                AssertionFailedError afe =
456 >                    new AssertionFailedError(t.toString());
457 >                afe.initCause(t);
458 >                throw afe;
459 >            }
460 >        }
461 >
462 >        if (Thread.interrupted())
463 >            throw new AssertionFailedError("interrupt status set in main thread");
464 >
465 >        checkForkJoinPoolThreadLeaks();
466 >    }
467 >
468 >    /**
469 >     * Finds missing try { ... } finally { joinPool(e); }
470 >     */
471 >    void checkForkJoinPoolThreadLeaks() throws InterruptedException {
472 >        Thread[] survivors = new Thread[5];
473 >        int count = Thread.enumerate(survivors);
474 >        for (int i = 0; i < count; i++) {
475 >            Thread thread = survivors[i];
476 >            String name = thread.getName();
477 >            if (name.startsWith("ForkJoinPool-")) {
478 >                // give thread some time to terminate
479 >                thread.join(LONG_DELAY_MS);
480 >                if (!thread.isAlive()) continue;
481 >                thread.stop();
482 >                throw new AssertionFailedError
483 >                    (String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n",
484 >                                   toString(), name));
485 >            }
486          }
487      }
488  
489      /**
490       * Just like fail(reason), but additionally recording (using
491 <     * threadRecordFailure) any AssertionError thrown, so that the current
492 <     * testcase will fail.
491 >     * threadRecordFailure) any AssertionFailedError thrown, so that
492 >     * the current testcase will fail.
493       */
494      public void threadFail(String reason) {
495          try {
496              fail(reason);
497 <        } catch (Throwable t) {
497 >        } catch (AssertionFailedError t) {
498              threadRecordFailure(t);
499              fail(reason);
500          }
# Line 272 | Line 502 | public class JSR166TestCase extends Test
502  
503      /**
504       * Just like assertTrue(b), but additionally recording (using
505 <     * threadRecordFailure) any AssertionError thrown, so that the current
506 <     * testcase will fail.
505 >     * threadRecordFailure) any AssertionFailedError thrown, so that
506 >     * the current testcase will fail.
507       */
508      public void threadAssertTrue(boolean b) {
509          try {
510              assertTrue(b);
511 <        } catch (AssertionError t) {
511 >        } catch (AssertionFailedError t) {
512              threadRecordFailure(t);
513              throw t;
514          }
# Line 286 | Line 516 | public class JSR166TestCase extends Test
516  
517      /**
518       * Just like assertFalse(b), but additionally recording (using
519 <     * threadRecordFailure) any AssertionError thrown, so that the
520 <     * current testcase will fail.
519 >     * threadRecordFailure) any AssertionFailedError thrown, so that
520 >     * the current testcase will fail.
521       */
522      public void threadAssertFalse(boolean b) {
523          try {
524              assertFalse(b);
525 <        } catch (AssertionError t) {
525 >        } catch (AssertionFailedError t) {
526              threadRecordFailure(t);
527              throw t;
528          }
# Line 300 | Line 530 | public class JSR166TestCase extends Test
530  
531      /**
532       * Just like assertNull(x), but additionally recording (using
533 <     * threadRecordFailure) any AssertionError thrown, so that the
534 <     * current testcase will fail.
533 >     * threadRecordFailure) any AssertionFailedError thrown, so that
534 >     * the current testcase will fail.
535       */
536      public void threadAssertNull(Object x) {
537          try {
538              assertNull(x);
539 <        } catch (AssertionError t) {
539 >        } catch (AssertionFailedError t) {
540              threadRecordFailure(t);
541              throw t;
542          }
# Line 314 | Line 544 | public class JSR166TestCase extends Test
544  
545      /**
546       * Just like assertEquals(x, y), but additionally recording (using
547 <     * threadRecordFailure) any AssertionError thrown, so that the
548 <     * current testcase will fail.
547 >     * threadRecordFailure) any AssertionFailedError thrown, so that
548 >     * the current testcase will fail.
549       */
550      public void threadAssertEquals(long x, long y) {
551          try {
552              assertEquals(x, y);
553 <        } catch (AssertionError t) {
553 >        } catch (AssertionFailedError t) {
554              threadRecordFailure(t);
555              throw t;
556          }
# Line 328 | Line 558 | public class JSR166TestCase extends Test
558  
559      /**
560       * Just like assertEquals(x, y), but additionally recording (using
561 <     * threadRecordFailure) any AssertionError thrown, so that the
562 <     * current testcase will fail.
561 >     * threadRecordFailure) any AssertionFailedError thrown, so that
562 >     * the current testcase will fail.
563       */
564      public void threadAssertEquals(Object x, Object y) {
565          try {
566              assertEquals(x, y);
567 <        } catch (AssertionError t) {
567 >        } catch (AssertionFailedError t) {
568              threadRecordFailure(t);
569              throw t;
570 +        } catch (Throwable t) {
571 +            threadUnexpectedException(t);
572          }
573      }
574  
575      /**
576       * Just like assertSame(x, y), but additionally recording (using
577 <     * threadRecordFailure) any AssertionError thrown, so that the
578 <     * current testcase will fail.
577 >     * threadRecordFailure) any AssertionFailedError thrown, so that
578 >     * the current testcase will fail.
579       */
580      public void threadAssertSame(Object x, Object y) {
581          try {
582              assertSame(x, y);
583 <        } catch (AssertionError t) {
583 >        } catch (AssertionFailedError t) {
584              threadRecordFailure(t);
585              throw t;
586          }
# Line 369 | Line 601 | public class JSR166TestCase extends Test
601      }
602  
603      /**
604 <     * Calls threadFail with message "Unexpected exception" + ex.
604 >     * Records the given exception using {@link #threadRecordFailure},
605 >     * then rethrows the exception, wrapping it in an
606 >     * AssertionFailedError if necessary.
607       */
608      public void threadUnexpectedException(Throwable t) {
609          threadRecordFailure(t);
610          t.printStackTrace();
377        // Rethrow, wrapping in an AssertionError if necessary
611          if (t instanceof RuntimeException)
612              throw (RuntimeException) t;
613          else if (t instanceof Error)
614              throw (Error) t;
615          else {
616 <            AssertionError ae = new AssertionError("unexpected exception: " + t);
617 <            t.initCause(t);
618 <            throw ae;
616 >            AssertionFailedError afe =
617 >                new AssertionFailedError("unexpected exception: " + t);
618 >            afe.initCause(t);
619 >            throw afe;
620 >        }
621 >    }
622 >
623 >    /**
624 >     * Delays, via Thread.sleep, for the given millisecond delay, but
625 >     * if the sleep is shorter than specified, may re-sleep or yield
626 >     * until time elapses.
627 >     */
628 >    static void delay(long millis) throws InterruptedException {
629 >        long startTime = System.nanoTime();
630 >        long ns = millis * 1000 * 1000;
631 >        for (;;) {
632 >            if (millis > 0L)
633 >                Thread.sleep(millis);
634 >            else // too short to sleep
635 >                Thread.yield();
636 >            long d = ns - (System.nanoTime() - startTime);
637 >            if (d > 0L)
638 >                millis = d / (1000 * 1000);
639 >            else
640 >                break;
641          }
642      }
643  
644      /**
645       * Waits out termination of a thread pool or fails doing so.
646       */
647 <    public void joinPool(ExecutorService exec) {
647 >    void joinPool(ExecutorService exec) {
648          try {
649              exec.shutdown();
650 <            assertTrue("ExecutorService did not terminate in a timely manner",
651 <                       exec.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
650 >            if (!exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS))
651 >                fail("ExecutorService " + exec +
652 >                     " did not terminate in a timely manner");
653          } catch (SecurityException ok) {
654              // Allowed in case test doesn't have privs
655          } catch (InterruptedException ie) {
# Line 401 | Line 657 | public class JSR166TestCase extends Test
657          }
658      }
659  
660 +    /**
661 +     * A debugging tool to print all stack traces, as jstack does.
662 +     */
663 +    static void printAllStackTraces() {
664 +        for (ThreadInfo info :
665 +                 ManagementFactory.getThreadMXBean()
666 +                 .dumpAllThreads(true, true))
667 +            System.err.print(info);
668 +    }
669 +
670 +    /**
671 +     * Checks that thread does not terminate within the default
672 +     * millisecond delay of {@code timeoutMillis()}.
673 +     */
674 +    void assertThreadStaysAlive(Thread thread) {
675 +        assertThreadStaysAlive(thread, timeoutMillis());
676 +    }
677 +
678 +    /**
679 +     * Checks that thread does not terminate within the given millisecond delay.
680 +     */
681 +    void assertThreadStaysAlive(Thread thread, long millis) {
682 +        try {
683 +            // No need to optimize the failing case via Thread.join.
684 +            delay(millis);
685 +            assertTrue(thread.isAlive());
686 +        } catch (InterruptedException ie) {
687 +            fail("Unexpected InterruptedException");
688 +        }
689 +    }
690 +
691 +    /**
692 +     * Checks that the threads do not terminate within the default
693 +     * millisecond delay of {@code timeoutMillis()}.
694 +     */
695 +    void assertThreadsStayAlive(Thread... threads) {
696 +        assertThreadsStayAlive(timeoutMillis(), threads);
697 +    }
698 +
699 +    /**
700 +     * Checks that the threads do not terminate within the given millisecond delay.
701 +     */
702 +    void assertThreadsStayAlive(long millis, Thread... threads) {
703 +        try {
704 +            // No need to optimize the failing case via Thread.join.
705 +            delay(millis);
706 +            for (Thread thread : threads)
707 +                assertTrue(thread.isAlive());
708 +        } catch (InterruptedException ie) {
709 +            fail("Unexpected InterruptedException");
710 +        }
711 +    }
712 +
713 +    /**
714 +     * Checks that future.get times out, with the default timeout of
715 +     * {@code timeoutMillis()}.
716 +     */
717 +    void assertFutureTimesOut(Future future) {
718 +        assertFutureTimesOut(future, timeoutMillis());
719 +    }
720 +
721 +    /**
722 +     * Checks that future.get times out, with the given millisecond timeout.
723 +     */
724 +    void assertFutureTimesOut(Future future, long timeoutMillis) {
725 +        long startTime = System.nanoTime();
726 +        try {
727 +            future.get(timeoutMillis, MILLISECONDS);
728 +            shouldThrow();
729 +        } catch (TimeoutException success) {
730 +        } catch (Exception e) {
731 +            threadUnexpectedException(e);
732 +        } finally { future.cancel(true); }
733 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
734 +    }
735  
736      /**
737       * Fails with message "should throw exception".
# Line 417 | Line 748 | public class JSR166TestCase extends Test
748      }
749  
750      /**
420     * Fails with message "Unexpected exception: " + ex.
421     */
422    public void unexpectedException(Throwable ex) {
423        ex.printStackTrace();
424        fail("Unexpected exception: " + ex);
425    }
426
427
428    /**
751       * The number of elements to place in collections, arrays, etc.
752       */
753      public static final int SIZE = 20;
# Line 450 | Line 772 | public class JSR166TestCase extends Test
772      public static final Integer m6  = new Integer(-6);
773      public static final Integer m10 = new Integer(-10);
774  
453
775      /**
776       * Runs Runnable r with a security policy that permits precisely
777       * the specified permissions.  If there is no current security
# Line 462 | Line 783 | public class JSR166TestCase extends Test
783          SecurityManager sm = System.getSecurityManager();
784          if (sm == null) {
785              r.run();
786 +        }
787 +        runWithSecurityManagerWithPermissions(r, permissions);
788 +    }
789 +
790 +    /**
791 +     * Runs Runnable r with a security policy that permits precisely
792 +     * the specified permissions.  If there is no current security
793 +     * manager, a temporary one is set for the duration of the
794 +     * Runnable.  We require that any security manager permit
795 +     * getPolicy/setPolicy.
796 +     */
797 +    public void runWithSecurityManagerWithPermissions(Runnable r,
798 +                                                      Permission... permissions) {
799 +        SecurityManager sm = System.getSecurityManager();
800 +        if (sm == null) {
801              Policy savedPolicy = Policy.getPolicy();
802              try {
803                  Policy.setPolicy(permissivePolicy());
804                  System.setSecurityManager(new SecurityManager());
805 <                runWithPermissions(r, permissions);
805 >                runWithSecurityManagerWithPermissions(r, permissions);
806              } finally {
807                  System.setSecurityManager(null);
808                  Policy.setPolicy(savedPolicy);
# Line 514 | Line 850 | public class JSR166TestCase extends Test
850              return perms.implies(p);
851          }
852          public void refresh() {}
853 +        public String toString() {
854 +            List<Permission> ps = new ArrayList<Permission>();
855 +            for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
856 +                ps.add(e.nextElement());
857 +            return "AdjustablePolicy with permissions " + ps;
858 +        }
859      }
860  
861      /**
# Line 536 | Line 878 | public class JSR166TestCase extends Test
878      }
879  
880      /**
881 <     * Sleep until the timeout has elapsed, or interrupted.
882 <     * Does <em>NOT</em> throw InterruptedException.
881 >     * Sleeps until the given time has elapsed.
882 >     * Throws AssertionFailedError if interrupted.
883 >     */
884 >    void sleep(long millis) {
885 >        try {
886 >            delay(millis);
887 >        } catch (InterruptedException ie) {
888 >            AssertionFailedError afe =
889 >                new AssertionFailedError("Unexpected InterruptedException");
890 >            afe.initCause(ie);
891 >            throw afe;
892 >        }
893 >    }
894 >
895 >    /**
896 >     * Spin-waits up to the specified number of milliseconds for the given
897 >     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
898 >     */
899 >    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
900 >        long startTime = System.nanoTime();
901 >        for (;;) {
902 >            Thread.State s = thread.getState();
903 >            if (s == Thread.State.BLOCKED ||
904 >                s == Thread.State.WAITING ||
905 >                s == Thread.State.TIMED_WAITING)
906 >                return;
907 >            else if (s == Thread.State.TERMINATED)
908 >                fail("Unexpected thread termination");
909 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
910 >                threadAssertTrue(thread.isAlive());
911 >                return;
912 >            }
913 >            Thread.yield();
914 >        }
915 >    }
916 >
917 >    /**
918 >     * Waits up to LONG_DELAY_MS for the given thread to enter a wait
919 >     * state: BLOCKED, WAITING, or TIMED_WAITING.
920 >     */
921 >    void waitForThreadToEnterWaitState(Thread thread) {
922 >        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
923 >    }
924 >
925 >    /**
926 >     * Returns the number of milliseconds since time given by
927 >     * startNanoTime, which must have been previously returned from a
928 >     * call to {@link System#nanoTime()}.
929 >     */
930 >    static long millisElapsedSince(long startNanoTime) {
931 >        return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
932 >    }
933 >
934 > //     void assertTerminatesPromptly(long timeoutMillis, Runnable r) {
935 > //         long startTime = System.nanoTime();
936 > //         try {
937 > //             r.run();
938 > //         } catch (Throwable fail) { threadUnexpectedException(fail); }
939 > //         if (millisElapsedSince(startTime) > timeoutMillis/2)
940 > //             throw new AssertionFailedError("did not return promptly");
941 > //     }
942 >
943 > //     void assertTerminatesPromptly(Runnable r) {
944 > //         assertTerminatesPromptly(LONG_DELAY_MS/2, r);
945 > //     }
946 >
947 >    /**
948 >     * Checks that timed f.get() returns the expected value, and does not
949 >     * wait for the timeout to elapse before returning.
950       */
951 <    void sleepTillInterrupted(long timeoutMillis) {
951 >    <T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) {
952 >        long startTime = System.nanoTime();
953          try {
954 <            Thread.sleep(timeoutMillis);
955 <        } catch (InterruptedException wakeup) {}
954 >            assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
955 >        } catch (Throwable fail) { threadUnexpectedException(fail); }
956 >        if (millisElapsedSince(startTime) > timeoutMillis/2)
957 >            throw new AssertionFailedError("timed get did not return promptly");
958 >    }
959 >
960 >    <T> void checkTimedGet(Future<T> f, T expectedValue) {
961 >        checkTimedGet(f, expectedValue, LONG_DELAY_MS);
962      }
963  
964      /**
965 <     * Returns a new started Thread running the given runnable.
965 >     * Returns a new started daemon Thread running the given runnable.
966       */
967      Thread newStartedThread(Runnable runnable) {
968          Thread t = new Thread(runnable);
969 +        t.setDaemon(true);
970          t.start();
971          return t;
972      }
973  
974 +    /**
975 +     * Waits for the specified time (in milliseconds) for the thread
976 +     * to terminate (using {@link Thread#join(long)}), else interrupts
977 +     * the thread (in the hope that it may terminate later) and fails.
978 +     */
979 +    void awaitTermination(Thread t, long timeoutMillis) {
980 +        try {
981 +            t.join(timeoutMillis);
982 +        } catch (InterruptedException ie) {
983 +            threadUnexpectedException(ie);
984 +        } finally {
985 +            if (t.getState() != Thread.State.TERMINATED) {
986 +                t.interrupt();
987 +                fail("Test timed out");
988 +            }
989 +        }
990 +    }
991 +
992 +    /**
993 +     * Waits for LONG_DELAY_MS milliseconds for the thread to
994 +     * terminate (using {@link Thread#join(long)}), else interrupts
995 +     * the thread (in the hope that it may terminate later) and fails.
996 +     */
997 +    void awaitTermination(Thread t) {
998 +        awaitTermination(t, LONG_DELAY_MS);
999 +    }
1000 +
1001      // Some convenient Runnable classes
1002  
1003      public abstract class CheckedRunnable implements Runnable {
# Line 616 | Line 1060 | public class JSR166TestCase extends Test
1060                  realRun();
1061                  threadShouldThrow("InterruptedException");
1062              } catch (InterruptedException success) {
1063 +                threadAssertFalse(Thread.interrupted());
1064              } catch (Throwable t) {
1065                  threadUnexpectedException(t);
1066              }
# Line 645 | Line 1090 | public class JSR166TestCase extends Test
1090                  threadShouldThrow("InterruptedException");
1091                  return result;
1092              } catch (InterruptedException success) {
1093 +                threadAssertFalse(Thread.interrupted());
1094              } catch (Throwable t) {
1095                  threadUnexpectedException(t);
1096              }
# Line 668 | Line 1114 | public class JSR166TestCase extends Test
1114  
1115      public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
1116          return new CheckedCallable<String>() {
1117 <            public String realCall() {
1117 >            protected String realCall() {
1118                  try {
1119                      latch.await();
1120                  } catch (InterruptedException quittingTime) {}
# Line 676 | Line 1122 | public class JSR166TestCase extends Test
1122              }};
1123      }
1124  
1125 +    public Runnable awaiter(final CountDownLatch latch) {
1126 +        return new CheckedRunnable() {
1127 +            public void realRun() throws InterruptedException {
1128 +                await(latch);
1129 +            }};
1130 +    }
1131 +
1132 +    public void await(CountDownLatch latch) {
1133 +        try {
1134 +            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1135 +        } catch (Throwable t) {
1136 +            threadUnexpectedException(t);
1137 +        }
1138 +    }
1139 +
1140 +    public void await(Semaphore semaphore) {
1141 +        try {
1142 +            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1143 +        } catch (Throwable t) {
1144 +            threadUnexpectedException(t);
1145 +        }
1146 +    }
1147 +
1148 + //     /**
1149 + //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1150 + //      */
1151 + //     public void await(AtomicBoolean flag) {
1152 + //         await(flag, LONG_DELAY_MS);
1153 + //     }
1154 +
1155 + //     /**
1156 + //      * Spin-waits up to the specified timeout until flag becomes true.
1157 + //      */
1158 + //     public void await(AtomicBoolean flag, long timeoutMillis) {
1159 + //         long startTime = System.nanoTime();
1160 + //         while (!flag.get()) {
1161 + //             if (millisElapsedSince(startTime) > timeoutMillis)
1162 + //                 throw new AssertionFailedError("timed out");
1163 + //             Thread.yield();
1164 + //         }
1165 + //     }
1166 +
1167      public static class NPETask implements Callable<String> {
1168          public String call() { throw new NullPointerException(); }
1169      }
# Line 686 | Line 1174 | public class JSR166TestCase extends Test
1174  
1175      public class ShortRunnable extends CheckedRunnable {
1176          protected void realRun() throws Throwable {
1177 <            Thread.sleep(SHORT_DELAY_MS);
1177 >            delay(SHORT_DELAY_MS);
1178          }
1179      }
1180  
1181      public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1182          protected void realRun() throws InterruptedException {
1183 <            Thread.sleep(SHORT_DELAY_MS);
1183 >            delay(SHORT_DELAY_MS);
1184          }
1185      }
1186  
1187      public class SmallRunnable extends CheckedRunnable {
1188          protected void realRun() throws Throwable {
1189 <            Thread.sleep(SMALL_DELAY_MS);
1189 >            delay(SMALL_DELAY_MS);
1190          }
1191      }
1192  
1193      public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1194          protected void realRun() {
1195              try {
1196 <                Thread.sleep(SMALL_DELAY_MS);
1196 >                delay(SMALL_DELAY_MS);
1197              } catch (InterruptedException ok) {}
1198          }
1199      }
1200  
1201      public class SmallCallable extends CheckedCallable {
1202          protected Object realCall() throws InterruptedException {
1203 <            Thread.sleep(SMALL_DELAY_MS);
1203 >            delay(SMALL_DELAY_MS);
1204              return Boolean.TRUE;
1205          }
1206      }
1207  
720    public class SmallInterruptedRunnable extends CheckedInterruptedRunnable {
721        protected void realRun() throws InterruptedException {
722            Thread.sleep(SMALL_DELAY_MS);
723        }
724    }
725
1208      public class MediumRunnable extends CheckedRunnable {
1209          protected void realRun() throws Throwable {
1210 <            Thread.sleep(MEDIUM_DELAY_MS);
1210 >            delay(MEDIUM_DELAY_MS);
1211          }
1212      }
1213  
1214      public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1215          protected void realRun() throws InterruptedException {
1216 <            Thread.sleep(MEDIUM_DELAY_MS);
1216 >            delay(MEDIUM_DELAY_MS);
1217          }
1218      }
1219  
1220 +    public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1221 +        return new CheckedRunnable() {
1222 +            protected void realRun() {
1223 +                try {
1224 +                    delay(timeoutMillis);
1225 +                } catch (InterruptedException ok) {}
1226 +            }};
1227 +    }
1228 +
1229      public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1230          protected void realRun() {
1231              try {
1232 <                Thread.sleep(MEDIUM_DELAY_MS);
1232 >                delay(MEDIUM_DELAY_MS);
1233              } catch (InterruptedException ok) {}
1234          }
1235      }
# Line 746 | Line 1237 | public class JSR166TestCase extends Test
1237      public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1238          protected void realRun() {
1239              try {
1240 <                Thread.sleep(LONG_DELAY_MS);
1240 >                delay(LONG_DELAY_MS);
1241              } catch (InterruptedException ok) {}
1242          }
1243      }
# Line 760 | Line 1251 | public class JSR166TestCase extends Test
1251          }
1252      }
1253  
1254 +    public interface TrackedRunnable extends Runnable {
1255 +        boolean isDone();
1256 +    }
1257 +
1258 +    public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
1259 +        return new TrackedRunnable() {
1260 +                private volatile boolean done = false;
1261 +                public boolean isDone() { return done; }
1262 +                public void run() {
1263 +                    try {
1264 +                        delay(timeoutMillis);
1265 +                        done = true;
1266 +                    } catch (InterruptedException ok) {}
1267 +                }
1268 +            };
1269 +    }
1270 +
1271      public static class TrackedShortRunnable implements Runnable {
1272          public volatile boolean done = false;
1273          public void run() {
1274              try {
1275 <                Thread.sleep(SMALL_DELAY_MS);
1275 >                delay(SHORT_DELAY_MS);
1276 >                done = true;
1277 >            } catch (InterruptedException ok) {}
1278 >        }
1279 >    }
1280 >
1281 >    public static class TrackedSmallRunnable implements Runnable {
1282 >        public volatile boolean done = false;
1283 >        public void run() {
1284 >            try {
1285 >                delay(SMALL_DELAY_MS);
1286                  done = true;
1287              } catch (InterruptedException ok) {}
1288          }
# Line 774 | Line 1292 | public class JSR166TestCase extends Test
1292          public volatile boolean done = false;
1293          public void run() {
1294              try {
1295 <                Thread.sleep(MEDIUM_DELAY_MS);
1295 >                delay(MEDIUM_DELAY_MS);
1296                  done = true;
1297              } catch (InterruptedException ok) {}
1298          }
# Line 784 | Line 1302 | public class JSR166TestCase extends Test
1302          public volatile boolean done = false;
1303          public void run() {
1304              try {
1305 <                Thread.sleep(LONG_DELAY_MS);
1305 >                delay(LONG_DELAY_MS);
1306                  done = true;
1307              } catch (InterruptedException ok) {}
1308          }
# Line 801 | Line 1319 | public class JSR166TestCase extends Test
1319          public volatile boolean done = false;
1320          public Object call() {
1321              try {
1322 <                Thread.sleep(SMALL_DELAY_MS);
1322 >                delay(SMALL_DELAY_MS);
1323                  done = true;
1324              } catch (InterruptedException ok) {}
1325              return Boolean.TRUE;
# Line 814 | Line 1332 | public class JSR166TestCase extends Test
1332      public abstract class CheckedRecursiveAction extends RecursiveAction {
1333          protected abstract void realCompute() throws Throwable;
1334  
1335 <        public final void compute() {
1335 >        @Override protected final void compute() {
1336              try {
1337                  realCompute();
1338              } catch (Throwable t) {
# Line 829 | Line 1347 | public class JSR166TestCase extends Test
1347      public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1348          protected abstract T realCompute() throws Throwable;
1349  
1350 <        public final T compute() {
1350 >        @Override protected final T compute() {
1351              try {
1352                  return realCompute();
1353              } catch (Throwable t) {
# Line 847 | Line 1365 | public class JSR166TestCase extends Test
1365                                        ThreadPoolExecutor executor) {}
1366      }
1367  
1368 +    /**
1369 +     * A CyclicBarrier that uses timed await and fails with
1370 +     * AssertionFailedErrors instead of throwing checked exceptions.
1371 +     */
1372 +    public class CheckedBarrier extends CyclicBarrier {
1373 +        public CheckedBarrier(int parties) { super(parties); }
1374 +
1375 +        public int await() {
1376 +            try {
1377 +                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1378 +            } catch (TimeoutException e) {
1379 +                throw new AssertionFailedError("timed out");
1380 +            } catch (Exception e) {
1381 +                AssertionFailedError afe =
1382 +                    new AssertionFailedError("Unexpected exception: " + e);
1383 +                afe.initCause(e);
1384 +                throw afe;
1385 +            }
1386 +        }
1387 +    }
1388 +
1389 +    void checkEmpty(BlockingQueue q) {
1390 +        try {
1391 +            assertTrue(q.isEmpty());
1392 +            assertEquals(0, q.size());
1393 +            assertNull(q.peek());
1394 +            assertNull(q.poll());
1395 +            assertNull(q.poll(0, MILLISECONDS));
1396 +            assertEquals(q.toString(), "[]");
1397 +            assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1398 +            assertFalse(q.iterator().hasNext());
1399 +            try {
1400 +                q.element();
1401 +                shouldThrow();
1402 +            } catch (NoSuchElementException success) {}
1403 +            try {
1404 +                q.iterator().next();
1405 +                shouldThrow();
1406 +            } catch (NoSuchElementException success) {}
1407 +            try {
1408 +                q.remove();
1409 +                shouldThrow();
1410 +            } catch (NoSuchElementException success) {}
1411 +        } catch (InterruptedException ie) {
1412 +            threadUnexpectedException(ie);
1413 +        }
1414 +    }
1415 +
1416 +    void assertSerialEquals(Object x, Object y) {
1417 +        assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1418 +    }
1419 +
1420 +    void assertNotSerialEquals(Object x, Object y) {
1421 +        assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1422 +    }
1423 +
1424 +    byte[] serialBytes(Object o) {
1425 +        try {
1426 +            ByteArrayOutputStream bos = new ByteArrayOutputStream();
1427 +            ObjectOutputStream oos = new ObjectOutputStream(bos);
1428 +            oos.writeObject(o);
1429 +            oos.flush();
1430 +            oos.close();
1431 +            return bos.toByteArray();
1432 +        } catch (Throwable t) {
1433 +            threadUnexpectedException(t);
1434 +            return new byte[0];
1435 +        }
1436 +    }
1437 +
1438 +    @SuppressWarnings("unchecked")
1439 +    <T> T serialClone(T o) {
1440 +        try {
1441 +            ObjectInputStream ois = new ObjectInputStream
1442 +                (new ByteArrayInputStream(serialBytes(o)));
1443 +            T clone = (T) ois.readObject();
1444 +            assertSame(o.getClass(), clone.getClass());
1445 +            return clone;
1446 +        } catch (Throwable t) {
1447 +            threadUnexpectedException(t);
1448 +            return null;
1449 +        }
1450 +    }
1451 +
1452 +    public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1453 +                             Runnable... throwingActions) {
1454 +        for (Runnable throwingAction : throwingActions) {
1455 +            boolean threw = false;
1456 +            try { throwingAction.run(); }
1457 +            catch (Throwable t) {
1458 +                threw = true;
1459 +                if (!expectedExceptionClass.isInstance(t)) {
1460 +                    AssertionFailedError afe =
1461 +                        new AssertionFailedError
1462 +                        ("Expected " + expectedExceptionClass.getName() +
1463 +                         ", got " + t.getClass().getName());
1464 +                    afe.initCause(t);
1465 +                    threadUnexpectedException(afe);
1466 +                }
1467 +            }
1468 +            if (!threw)
1469 +                shouldThrow(expectedExceptionClass.getName());
1470 +        }
1471 +    }
1472 +
1473 +    public void assertIteratorExhausted(Iterator<?> it) {
1474 +        try {
1475 +            it.next();
1476 +            shouldThrow();
1477 +        } catch (NoSuchElementException success) {}
1478 +        assertFalse(it.hasNext());
1479 +    }        
1480   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines