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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines