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.52 by jsr166, Mon Sep 13 23:19:31 2010 UTC vs.
Revision 1.108 by jsr166, Mon Jun 3 18:20:05 2013 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.*;
10 > import java.io.ByteArrayInputStream;
11 > import java.io.ByteArrayOutputStream;
12 > import java.io.ObjectInputStream;
13 > import java.io.ObjectOutputStream;
14 > import java.lang.management.ManagementFactory;
15 > import java.lang.management.ThreadInfo;
16 > import java.lang.reflect.Method;
17 > import java.util.ArrayList;
18 > import java.util.Arrays;
19 > import java.util.Date;
20 > import java.util.Enumeration;
21 > import java.util.List;
22 > import java.util.NoSuchElementException;
23 > import java.util.PropertyPermission;
24   import java.util.concurrent.*;
25 + import java.util.concurrent.atomic.AtomicBoolean;
26 + import java.util.concurrent.atomic.AtomicReference;
27   import static java.util.concurrent.TimeUnit.MILLISECONDS;
28 < import java.io.*;
29 < import java.security.*;
28 > import static java.util.concurrent.TimeUnit.NANOSECONDS;
29 > import java.security.CodeSource;
30 > import java.security.Permission;
31 > import java.security.PermissionCollection;
32 > import java.security.Permissions;
33 > import java.security.Policy;
34 > import java.security.ProtectionDomain;
35 > import java.security.SecurityPermission;
36  
37   /**
38   * Base class for JSR166 Junit TCK tests.  Defines some constants,
# Line 54 | Line 75 | import java.security.*;
75   *
76   * </ol>
77   *
78 < * <p> <b>Other notes</b>
78 > * <p><b>Other notes</b>
79   * <ul>
80   *
81   * <li> Usually, there is one testcase method per JSR166 method
# Line 90 | Line 111 | public class JSR166TestCase extends Test
111      private static final boolean useSecurityManager =
112          Boolean.getBoolean("jsr166.useSecurityManager");
113  
114 +    protected static final boolean expensiveTests =
115 +        Boolean.getBoolean("jsr166.expensiveTests");
116 +
117 +    /**
118 +     * If true, report on stdout all "slow" tests, that is, ones that
119 +     * take more than profileThreshold milliseconds to execute.
120 +     */
121 +    private static final boolean profileTests =
122 +        Boolean.getBoolean("jsr166.profileTests");
123 +
124 +    /**
125 +     * The number of milliseconds that tests are permitted for
126 +     * execution without being reported, when profileTests is set.
127 +     */
128 +    private static final long profileThreshold =
129 +        Long.getLong("jsr166.profileThreshold", 100);
130 +
131 +    /**
132 +     * The number of repetitions per test (for tickling rare bugs).
133 +     */
134 +    private static final int runsPerTest =
135 +        Integer.getInteger("jsr166.runsPerTest", 1);
136 +
137 +    protected void runTest() throws Throwable {
138 +        for (int i = 0; i < runsPerTest; i++) {
139 +            if (profileTests)
140 +                runTestProfiled();
141 +            else
142 +                super.runTest();
143 +        }
144 +    }
145 +
146 +    protected void runTestProfiled() throws Throwable {
147 +        long t0 = System.nanoTime();
148 +        try {
149 +            super.runTest();
150 +        } finally {
151 +            long elapsedMillis =
152 +                (System.nanoTime() - t0) / (1000L * 1000L);
153 +            if (elapsedMillis >= profileThreshold)
154 +                System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
155 +        }
156 +    }
157 +
158      /**
159 <     * Runs all JSR166 unit tests using junit.textui.TestRunner
159 >     * Runs all JSR166 unit tests using junit.textui.TestRunner.
160 >     * Optional command line arg provides the number of iterations to
161 >     * repeat running the tests.
162       */
163      public static void main(String[] args) {
164          if (useSecurityManager) {
# Line 99 | Line 166 | public class JSR166TestCase extends Test
166              Policy.setPolicy(permissivePolicy());
167              System.setSecurityManager(new SecurityManager());
168          }
169 <        int iters = 1;
170 <        if (args.length > 0)
104 <            iters = Integer.parseInt(args[0]);
169 >        int iters = (args.length == 0) ? 1 : Integer.parseInt(args[0]);
170 >
171          Test s = suite();
172          for (int i = 0; i < iters; ++i) {
173              junit.textui.TestRunner.run(s);
# Line 111 | Line 177 | public class JSR166TestCase extends Test
177          System.exit(0);
178      }
179  
180 +    public static TestSuite newTestSuite(Object... suiteOrClasses) {
181 +        TestSuite suite = new TestSuite();
182 +        for (Object suiteOrClass : suiteOrClasses) {
183 +            if (suiteOrClass instanceof TestSuite)
184 +                suite.addTest((TestSuite) suiteOrClass);
185 +            else if (suiteOrClass instanceof Class)
186 +                suite.addTest(new TestSuite((Class<?>) suiteOrClass));
187 +            else
188 +                throw new ClassCastException("not a test suite or class");
189 +        }
190 +        return suite;
191 +    }
192 +
193 +    public static void addNamedTestClasses(TestSuite suite,
194 +                                           String... testClassNames) {
195 +        for (String testClassName : testClassNames) {
196 +            try {
197 +                Class<?> testClass = Class.forName(testClassName);
198 +                Method m = testClass.getDeclaredMethod("suite",
199 +                                                       new Class<?>[0]);
200 +                suite.addTest(newTestSuite((Test)m.invoke(null)));
201 +            } catch (Exception e) {
202 +                throw new Error("Missing test class", e);
203 +            }
204 +        }
205 +    }
206 +
207 +    public static final double JAVA_CLASS_VERSION;
208 +    static {
209 +        try {
210 +            JAVA_CLASS_VERSION = java.security.AccessController.doPrivileged(
211 +                new java.security.PrivilegedAction<Double>() {
212 +                public Double run() {
213 +                    return Double.valueOf(System.getProperty("java.class.version"));}});
214 +        } catch (Throwable t) {
215 +            throw new Error(t);
216 +        }
217 +    }
218 +
219 +    public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
220 +    public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
221 +    public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
222 +
223      /**
224 <     * Collects all JSR166 unit tests as one suite
224 >     * Collects all JSR166 unit tests as one suite.
225       */
226      public static Test suite() {
227 <        TestSuite suite = new TestSuite("JSR166 Unit Tests");
228 <
229 <        suite.addTest(new TestSuite(ForkJoinPoolTest.class));
230 <        suite.addTest(new TestSuite(ForkJoinTaskTest.class));
231 <        suite.addTest(new TestSuite(RecursiveActionTest.class));
232 <        suite.addTest(new TestSuite(RecursiveTaskTest.class));
233 <        suite.addTest(new TestSuite(LinkedTransferQueueTest.class));
234 <        suite.addTest(new TestSuite(PhaserTest.class));
235 <        suite.addTest(new TestSuite(ThreadLocalRandomTest.class));
236 <        suite.addTest(new TestSuite(AbstractExecutorServiceTest.class));
237 <        suite.addTest(new TestSuite(AbstractQueueTest.class));
238 <        suite.addTest(new TestSuite(AbstractQueuedSynchronizerTest.class));
239 <        suite.addTest(new TestSuite(AbstractQueuedLongSynchronizerTest.class));
240 <        suite.addTest(new TestSuite(ArrayBlockingQueueTest.class));
241 <        suite.addTest(new TestSuite(ArrayDequeTest.class));
242 <        suite.addTest(new TestSuite(AtomicBooleanTest.class));
243 <        suite.addTest(new TestSuite(AtomicIntegerArrayTest.class));
244 <        suite.addTest(new TestSuite(AtomicIntegerFieldUpdaterTest.class));
245 <        suite.addTest(new TestSuite(AtomicIntegerTest.class));
246 <        suite.addTest(new TestSuite(AtomicLongArrayTest.class));
247 <        suite.addTest(new TestSuite(AtomicLongFieldUpdaterTest.class));
248 <        suite.addTest(new TestSuite(AtomicLongTest.class));
249 <        suite.addTest(new TestSuite(AtomicMarkableReferenceTest.class));
250 <        suite.addTest(new TestSuite(AtomicReferenceArrayTest.class));
251 <        suite.addTest(new TestSuite(AtomicReferenceFieldUpdaterTest.class));
252 <        suite.addTest(new TestSuite(AtomicReferenceTest.class));
253 <        suite.addTest(new TestSuite(AtomicStampedReferenceTest.class));
254 <        suite.addTest(new TestSuite(ConcurrentHashMapTest.class));
255 <        suite.addTest(new TestSuite(ConcurrentLinkedDequeTest.class));
256 <        suite.addTest(new TestSuite(ConcurrentLinkedQueueTest.class));
257 <        suite.addTest(new TestSuite(ConcurrentSkipListMapTest.class));
258 <        suite.addTest(new TestSuite(ConcurrentSkipListSubMapTest.class));
259 <        suite.addTest(new TestSuite(ConcurrentSkipListSetTest.class));
260 <        suite.addTest(new TestSuite(ConcurrentSkipListSubSetTest.class));
261 <        suite.addTest(new TestSuite(CopyOnWriteArrayListTest.class));
262 <        suite.addTest(new TestSuite(CopyOnWriteArraySetTest.class));
263 <        suite.addTest(new TestSuite(CountDownLatchTest.class));
264 <        suite.addTest(new TestSuite(CyclicBarrierTest.class));
265 <        suite.addTest(new TestSuite(DelayQueueTest.class));
266 <        suite.addTest(new TestSuite(EntryTest.class));
267 <        suite.addTest(new TestSuite(ExchangerTest.class));
268 <        suite.addTest(new TestSuite(ExecutorsTest.class));
269 <        suite.addTest(new TestSuite(ExecutorCompletionServiceTest.class));
270 <        suite.addTest(new TestSuite(FutureTaskTest.class));
271 <        suite.addTest(new TestSuite(LinkedBlockingDequeTest.class));
272 <        suite.addTest(new TestSuite(LinkedBlockingQueueTest.class));
273 <        suite.addTest(new TestSuite(LinkedListTest.class));
274 <        suite.addTest(new TestSuite(LockSupportTest.class));
275 <        suite.addTest(new TestSuite(PriorityBlockingQueueTest.class));
276 <        suite.addTest(new TestSuite(PriorityQueueTest.class));
277 <        suite.addTest(new TestSuite(ReentrantLockTest.class));
278 <        suite.addTest(new TestSuite(ReentrantReadWriteLockTest.class));
279 <        suite.addTest(new TestSuite(ScheduledExecutorTest.class));
280 <        suite.addTest(new TestSuite(ScheduledExecutorSubclassTest.class));
281 <        suite.addTest(new TestSuite(SemaphoreTest.class));
282 <        suite.addTest(new TestSuite(SynchronousQueueTest.class));
283 <        suite.addTest(new TestSuite(SystemTest.class));
284 <        suite.addTest(new TestSuite(ThreadLocalTest.class));
285 <        suite.addTest(new TestSuite(ThreadPoolExecutorTest.class));
286 <        suite.addTest(new TestSuite(ThreadPoolExecutorSubclassTest.class));
287 <        suite.addTest(new TestSuite(ThreadTest.class));
288 <        suite.addTest(new TestSuite(TimeUnitTest.class));
289 <        suite.addTest(new TestSuite(TreeMapTest.class));
290 <        suite.addTest(new TestSuite(TreeSetTest.class));
291 <        suite.addTest(new TestSuite(TreeSubMapTest.class));
292 <        suite.addTest(new TestSuite(TreeSubSetTest.class));
227 >        // Java7+ test classes
228 >        TestSuite suite = newTestSuite(
229 >            ForkJoinPoolTest.suite(),
230 >            ForkJoinTaskTest.suite(),
231 >            RecursiveActionTest.suite(),
232 >            RecursiveTaskTest.suite(),
233 >            LinkedTransferQueueTest.suite(),
234 >            PhaserTest.suite(),
235 >            ThreadLocalRandomTest.suite(),
236 >            AbstractExecutorServiceTest.suite(),
237 >            AbstractQueueTest.suite(),
238 >            AbstractQueuedSynchronizerTest.suite(),
239 >            AbstractQueuedLongSynchronizerTest.suite(),
240 >            ArrayBlockingQueueTest.suite(),
241 >            ArrayDequeTest.suite(),
242 >            AtomicBooleanTest.suite(),
243 >            AtomicIntegerArrayTest.suite(),
244 >            AtomicIntegerFieldUpdaterTest.suite(),
245 >            AtomicIntegerTest.suite(),
246 >            AtomicLongArrayTest.suite(),
247 >            AtomicLongFieldUpdaterTest.suite(),
248 >            AtomicLongTest.suite(),
249 >            AtomicMarkableReferenceTest.suite(),
250 >            AtomicReferenceArrayTest.suite(),
251 >            AtomicReferenceFieldUpdaterTest.suite(),
252 >            AtomicReferenceTest.suite(),
253 >            AtomicStampedReferenceTest.suite(),
254 >            ConcurrentHashMapTest.suite(),
255 >            ConcurrentLinkedDequeTest.suite(),
256 >            ConcurrentLinkedQueueTest.suite(),
257 >            ConcurrentSkipListMapTest.suite(),
258 >            ConcurrentSkipListSubMapTest.suite(),
259 >            ConcurrentSkipListSetTest.suite(),
260 >            ConcurrentSkipListSubSetTest.suite(),
261 >            CopyOnWriteArrayListTest.suite(),
262 >            CopyOnWriteArraySetTest.suite(),
263 >            CountDownLatchTest.suite(),
264 >            CyclicBarrierTest.suite(),
265 >            DelayQueueTest.suite(),
266 >            EntryTest.suite(),
267 >            ExchangerTest.suite(),
268 >            ExecutorsTest.suite(),
269 >            ExecutorCompletionServiceTest.suite(),
270 >            FutureTaskTest.suite(),
271 >            LinkedBlockingDequeTest.suite(),
272 >            LinkedBlockingQueueTest.suite(),
273 >            LinkedListTest.suite(),
274 >            LockSupportTest.suite(),
275 >            PriorityBlockingQueueTest.suite(),
276 >            PriorityQueueTest.suite(),
277 >            ReentrantLockTest.suite(),
278 >            ReentrantReadWriteLockTest.suite(),
279 >            ScheduledExecutorTest.suite(),
280 >            ScheduledExecutorSubclassTest.suite(),
281 >            SemaphoreTest.suite(),
282 >            SynchronousQueueTest.suite(),
283 >            SystemTest.suite(),
284 >            ThreadLocalTest.suite(),
285 >            ThreadPoolExecutorTest.suite(),
286 >            ThreadPoolExecutorSubclassTest.suite(),
287 >            ThreadTest.suite(),
288 >            TimeUnitTest.suite(),
289 >            TreeMapTest.suite(),
290 >            TreeSetTest.suite(),
291 >            TreeSubMapTest.suite(),
292 >            TreeSubSetTest.suite());
293 >
294 >        // Java8+ test classes
295 >        if (atLeastJava8()) {
296 >            String[] java8TestClassNames = {
297 >                "CompletableFutureTest",
298 >                "ConcurrentHashMap8Test",
299 >                "CountedCompleterTest",
300 >                "DoubleAccumulatorTest",
301 >                "DoubleAdderTest",
302 >                "ForkJoinPool8Test",
303 >                "LongAccumulatorTest",
304 >                "LongAdderTest",
305 >                "StampedLockTest",
306 >            };
307 >            addNamedTestClasses(suite, java8TestClassNames);
308 >        }
309  
310          return suite;
311      }
# Line 200 | Line 325 | public class JSR166TestCase extends Test
325          return 50;
326      }
327  
203
328      /**
329       * Sets delays as multiples of SHORT_DELAY.
330       */
331      protected void setDelays() {
332          SHORT_DELAY_MS = getShortDelay();
333 <        SMALL_DELAY_MS = SHORT_DELAY_MS * 5;
333 >        SMALL_DELAY_MS  = SHORT_DELAY_MS * 5;
334          MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
335 <        LONG_DELAY_MS = SHORT_DELAY_MS * 50;
335 >        LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
336 >    }
337 >
338 >    /**
339 >     * Returns a timeout in milliseconds to be used in tests that
340 >     * verify that operations block or time out.
341 >     */
342 >    long timeoutMillis() {
343 >        return SHORT_DELAY_MS / 4;
344 >    }
345 >
346 >    /**
347 >     * Returns a new Date instance representing a time delayMillis
348 >     * milliseconds in the future.
349 >     */
350 >    Date delayedDate(long delayMillis) {
351 >        return new Date(System.currentTimeMillis() + delayMillis);
352      }
353  
354      /**
355 <     * Flag set true if any threadAssert methods fail
355 >     * The first exception encountered if any threadAssertXXX method fails.
356       */
357 <    volatile boolean threadFailed;
357 >    private final AtomicReference<Throwable> threadFailure
358 >        = new AtomicReference<Throwable>(null);
359  
360      /**
361 <     * Initializes test to indicate that no thread assertions have failed
361 >     * Records an exception so that it can be rethrown later in the test
362 >     * harness thread, triggering a test case failure.  Only the first
363 >     * failure is recorded; subsequent calls to this method from within
364 >     * the same test have no effect.
365       */
366 +    public void threadRecordFailure(Throwable t) {
367 +        threadFailure.compareAndSet(null, t);
368 +    }
369 +
370      public void setUp() {
371          setDelays();
224        threadFailed = false;
372      }
373  
374      /**
375 <     * Triggers test case failure if any thread assertions have failed
375 >     * Extra checks that get done for all test cases.
376 >     *
377 >     * Triggers test case failure if any thread assertions have failed,
378 >     * by rethrowing, in the test harness thread, any exception recorded
379 >     * earlier by threadRecordFailure.
380 >     *
381 >     * Triggers test case failure if interrupt status is set in the main thread.
382 >     */
383 >    public void tearDown() throws Exception {
384 >        Throwable t = threadFailure.getAndSet(null);
385 >        if (t != null) {
386 >            if (t instanceof Error)
387 >                throw (Error) t;
388 >            else if (t instanceof RuntimeException)
389 >                throw (RuntimeException) t;
390 >            else if (t instanceof Exception)
391 >                throw (Exception) t;
392 >            else {
393 >                AssertionFailedError afe =
394 >                    new AssertionFailedError(t.toString());
395 >                afe.initCause(t);
396 >                throw afe;
397 >            }
398 >        }
399 >
400 >        if (Thread.interrupted())
401 >            throw new AssertionFailedError("interrupt status set in main thread");
402 >
403 >        checkForkJoinPoolThreadLeaks();
404 >    }
405 >
406 >    /**
407 >     * Find missing try { ... } finally { joinPool(e); }
408       */
409 <    public void tearDown() {
410 <        assertFalse(threadFailed);
409 >    void checkForkJoinPoolThreadLeaks() throws InterruptedException {
410 >        Thread[] survivors = new Thread[5];
411 >        int count = Thread.enumerate(survivors);
412 >        for (int i = 0; i < count; i++) {
413 >            Thread thread = survivors[i];
414 >            String name = thread.getName();
415 >            if (name.startsWith("ForkJoinPool-")) {
416 >                // give thread some time to terminate
417 >                thread.join(LONG_DELAY_MS);
418 >                if (!thread.isAlive()) continue;
419 >                thread.stop();
420 >                throw new AssertionFailedError
421 >                    (String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n",
422 >                                   toString(), name));
423 >            }
424 >        }
425      }
426  
427      /**
428 <     * Fail, also setting status to indicate current testcase should fail
428 >     * Just like fail(reason), but additionally recording (using
429 >     * threadRecordFailure) any AssertionFailedError thrown, so that
430 >     * the current testcase will fail.
431       */
432      public void threadFail(String reason) {
433 <        threadFailed = true;
434 <        fail(reason);
433 >        try {
434 >            fail(reason);
435 >        } catch (AssertionFailedError t) {
436 >            threadRecordFailure(t);
437 >            fail(reason);
438 >        }
439      }
440  
441      /**
442 <     * If expression not true, set status to indicate current testcase
443 <     * should fail
442 >     * Just like assertTrue(b), but additionally recording (using
443 >     * threadRecordFailure) any AssertionFailedError thrown, so that
444 >     * the current testcase will fail.
445       */
446      public void threadAssertTrue(boolean b) {
447 <        if (!b) {
248 <            threadFailed = true;
447 >        try {
448              assertTrue(b);
449 +        } catch (AssertionFailedError t) {
450 +            threadRecordFailure(t);
451 +            throw t;
452          }
453      }
454  
455      /**
456 <     * If expression not false, set status to indicate current testcase
457 <     * should fail
456 >     * Just like assertFalse(b), but additionally recording (using
457 >     * threadRecordFailure) any AssertionFailedError thrown, so that
458 >     * the current testcase will fail.
459       */
460      public void threadAssertFalse(boolean b) {
461 <        if (b) {
259 <            threadFailed = true;
461 >        try {
462              assertFalse(b);
463 +        } catch (AssertionFailedError t) {
464 +            threadRecordFailure(t);
465 +            throw t;
466          }
467      }
468  
469      /**
470 <     * If argument not null, set status to indicate current testcase
471 <     * should fail
470 >     * Just like assertNull(x), but additionally recording (using
471 >     * threadRecordFailure) any AssertionFailedError thrown, so that
472 >     * the current testcase will fail.
473       */
474      public void threadAssertNull(Object x) {
475 <        if (x != null) {
270 <            threadFailed = true;
475 >        try {
476              assertNull(x);
477 +        } catch (AssertionFailedError t) {
478 +            threadRecordFailure(t);
479 +            throw t;
480          }
481      }
482  
483      /**
484 <     * If arguments not equal, set status to indicate current testcase
485 <     * should fail
484 >     * Just like assertEquals(x, y), but additionally recording (using
485 >     * threadRecordFailure) any AssertionFailedError thrown, so that
486 >     * the current testcase will fail.
487       */
488      public void threadAssertEquals(long x, long y) {
489 <        if (x != y) {
281 <            threadFailed = true;
489 >        try {
490              assertEquals(x, y);
491 +        } catch (AssertionFailedError t) {
492 +            threadRecordFailure(t);
493 +            throw t;
494          }
495      }
496  
497      /**
498 <     * If arguments not equal, set status to indicate current testcase
499 <     * should fail
498 >     * Just like assertEquals(x, y), but additionally recording (using
499 >     * threadRecordFailure) any AssertionFailedError thrown, so that
500 >     * the current testcase will fail.
501       */
502      public void threadAssertEquals(Object x, Object y) {
503 <        if (x != y && (x == null || !x.equals(y))) {
292 <            threadFailed = true;
503 >        try {
504              assertEquals(x, y);
505 +        } catch (AssertionFailedError t) {
506 +            threadRecordFailure(t);
507 +            throw t;
508 +        } catch (Throwable t) {
509 +            threadUnexpectedException(t);
510          }
511      }
512  
513      /**
514 <     * If arguments not identical, set status to indicate current testcase
515 <     * should fail
514 >     * Just like assertSame(x, y), but additionally recording (using
515 >     * threadRecordFailure) any AssertionFailedError thrown, so that
516 >     * the current testcase will fail.
517       */
518      public void threadAssertSame(Object x, Object y) {
519 <        if (x != y) {
303 <            threadFailed = true;
519 >        try {
520              assertSame(x, y);
521 +        } catch (AssertionFailedError t) {
522 +            threadRecordFailure(t);
523 +            throw t;
524          }
525      }
526  
527      /**
528 <     * threadFail with message "should throw exception"
528 >     * Calls threadFail with message "should throw exception".
529       */
530      public void threadShouldThrow() {
531 <        threadFailed = true;
313 <        fail("should throw exception");
531 >        threadFail("should throw exception");
532      }
533  
534      /**
535 <     * threadFail with message "should throw" + exceptionName
535 >     * Calls threadFail with message "should throw" + exceptionName.
536       */
537      public void threadShouldThrow(String exceptionName) {
538 <        threadFailed = true;
321 <        fail("should throw " + exceptionName);
538 >        threadFail("should throw " + exceptionName);
539      }
540  
541      /**
542 <     * threadFail with message "Unexpected exception"
542 >     * Records the given exception using {@link #threadRecordFailure},
543 >     * then rethrows the exception, wrapping it in an
544 >     * AssertionFailedError if necessary.
545       */
546 <    public void threadUnexpectedException() {
547 <        threadFailed = true;
548 <        fail("Unexpected exception");
546 >    public void threadUnexpectedException(Throwable t) {
547 >        threadRecordFailure(t);
548 >        t.printStackTrace();
549 >        if (t instanceof RuntimeException)
550 >            throw (RuntimeException) t;
551 >        else if (t instanceof Error)
552 >            throw (Error) t;
553 >        else {
554 >            AssertionFailedError afe =
555 >                new AssertionFailedError("unexpected exception: " + t);
556 >            afe.initCause(t);
557 >            throw afe;
558 >        }
559      }
560  
561      /**
562 <     * threadFail with message "Unexpected exception", with argument
562 >     * Delays, via Thread.sleep, for the given millisecond delay, but
563 >     * if the sleep is shorter than specified, may re-sleep or yield
564 >     * until time elapses.
565       */
566 <    public void threadUnexpectedException(Throwable ex) {
567 <        threadFailed = true;
568 <        ex.printStackTrace();
569 <        fail("Unexpected exception: " + ex);
566 >    static void delay(long millis) throws InterruptedException {
567 >        long startTime = System.nanoTime();
568 >        long ns = millis * 1000 * 1000;
569 >        for (;;) {
570 >            if (millis > 0L)
571 >                Thread.sleep(millis);
572 >            else // too short to sleep
573 >                Thread.yield();
574 >            long d = ns - (System.nanoTime() - startTime);
575 >            if (d > 0L)
576 >                millis = d / (1000 * 1000);
577 >            else
578 >                break;
579 >        }
580      }
581  
582      /**
583 <     * Wait out termination of a thread pool or fail doing so
583 >     * Waits out termination of a thread pool or fails doing so.
584       */
585 <    public void joinPool(ExecutorService exec) {
585 >    void joinPool(ExecutorService exec) {
586          try {
587              exec.shutdown();
588 <            assertTrue(exec.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
588 >            assertTrue("ExecutorService did not terminate in a timely manner",
589 >                       exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS));
590          } catch (SecurityException ok) {
591              // Allowed in case test doesn't have privs
592          } catch (InterruptedException ie) {
# Line 352 | Line 594 | public class JSR166TestCase extends Test
594          }
595      }
596  
597 +    /**
598 +     * A debugging tool to print all stack traces, as jstack does.
599 +     */
600 +    static void printAllStackTraces() {
601 +        for (ThreadInfo info :
602 +                 ManagementFactory.getThreadMXBean()
603 +                 .dumpAllThreads(true, true))
604 +            System.err.print(info);
605 +    }
606  
607      /**
608 <     * fail with message "should throw exception"
608 >     * Checks that thread does not terminate within the default
609 >     * millisecond delay of {@code timeoutMillis()}.
610       */
611 <    public void shouldThrow() {
612 <        fail("Should throw exception");
611 >    void assertThreadStaysAlive(Thread thread) {
612 >        assertThreadStaysAlive(thread, timeoutMillis());
613      }
614  
615      /**
616 <     * fail with message "should throw " + exceptionName
616 >     * Checks that thread does not terminate within the given millisecond delay.
617       */
618 <    public void shouldThrow(String exceptionName) {
619 <        fail("Should throw " + exceptionName);
618 >    void assertThreadStaysAlive(Thread thread, long millis) {
619 >        try {
620 >            // No need to optimize the failing case via Thread.join.
621 >            delay(millis);
622 >            assertTrue(thread.isAlive());
623 >        } catch (InterruptedException ie) {
624 >            fail("Unexpected InterruptedException");
625 >        }
626      }
627  
628      /**
629 <     * fail with message "Unexpected exception"
629 >     * Checks that the threads do not terminate within the default
630 >     * millisecond delay of {@code timeoutMillis()}.
631       */
632 <    public void unexpectedException() {
633 <        fail("Unexpected exception");
632 >    void assertThreadsStayAlive(Thread... threads) {
633 >        assertThreadsStayAlive(timeoutMillis(), threads);
634      }
635  
636      /**
637 <     * fail with message "Unexpected exception", with argument
637 >     * Checks that the threads do not terminate within the given millisecond delay.
638       */
639 <    public void unexpectedException(Throwable ex) {
640 <        ex.printStackTrace();
641 <        fail("Unexpected exception: " + ex);
639 >    void assertThreadsStayAlive(long millis, Thread... threads) {
640 >        try {
641 >            // No need to optimize the failing case via Thread.join.
642 >            delay(millis);
643 >            for (Thread thread : threads)
644 >                assertTrue(thread.isAlive());
645 >        } catch (InterruptedException ie) {
646 >            fail("Unexpected InterruptedException");
647 >        }
648      }
649  
650 +    /**
651 +     * Checks that future.get times out, with the default timeout of
652 +     * {@code timeoutMillis()}.
653 +     */
654 +    void assertFutureTimesOut(Future future) {
655 +        assertFutureTimesOut(future, timeoutMillis());
656 +    }
657 +
658 +    /**
659 +     * Checks that future.get times out, with the given millisecond timeout.
660 +     */
661 +    void assertFutureTimesOut(Future future, long timeoutMillis) {
662 +        long startTime = System.nanoTime();
663 +        try {
664 +            future.get(timeoutMillis, MILLISECONDS);
665 +            shouldThrow();
666 +        } catch (TimeoutException success) {
667 +        } catch (Exception e) {
668 +            threadUnexpectedException(e);
669 +        } finally { future.cancel(true); }
670 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
671 +    }
672 +
673 +    /**
674 +     * Fails with message "should throw exception".
675 +     */
676 +    public void shouldThrow() {
677 +        fail("Should throw exception");
678 +    }
679 +
680 +    /**
681 +     * Fails with message "should throw " + exceptionName.
682 +     */
683 +    public void shouldThrow(String exceptionName) {
684 +        fail("Should throw " + exceptionName);
685 +    }
686  
687      /**
688       * The number of elements to place in collections, arrays, etc.
# Line 420 | Line 721 | public class JSR166TestCase extends Test
721          SecurityManager sm = System.getSecurityManager();
722          if (sm == null) {
723              r.run();
724 +        }
725 +        runWithSecurityManagerWithPermissions(r, permissions);
726 +    }
727 +
728 +    /**
729 +     * Runs Runnable r with a security policy that permits precisely
730 +     * the specified permissions.  If there is no current security
731 +     * manager, a temporary one is set for the duration of the
732 +     * Runnable.  We require that any security manager permit
733 +     * getPolicy/setPolicy.
734 +     */
735 +    public void runWithSecurityManagerWithPermissions(Runnable r,
736 +                                                      Permission... permissions) {
737 +        SecurityManager sm = System.getSecurityManager();
738 +        if (sm == null) {
739              Policy savedPolicy = Policy.getPolicy();
740              try {
741                  Policy.setPolicy(permissivePolicy());
742                  System.setSecurityManager(new SecurityManager());
743 <                runWithPermissions(r, permissions);
743 >                runWithSecurityManagerWithPermissions(r, permissions);
744              } finally {
745                  System.setSecurityManager(null);
746                  Policy.setPolicy(savedPolicy);
# Line 472 | Line 788 | public class JSR166TestCase extends Test
788              return perms.implies(p);
789          }
790          public void refresh() {}
791 +        public String toString() {
792 +            List<Permission> ps = new ArrayList<Permission>();
793 +            for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
794 +                ps.add(e.nextElement());
795 +            return "AdjustablePolicy with permissions " + ps;
796 +        }
797      }
798  
799      /**
# Line 494 | Line 816 | public class JSR166TestCase extends Test
816      }
817  
818      /**
819 <     * Sleep until the timeout has elapsed, or interrupted.
820 <     * Does <em>NOT</em> throw InterruptedException.
819 >     * Sleeps until the given time has elapsed.
820 >     * Throws AssertionFailedError if interrupted.
821       */
822 <    void sleepTillInterrupted(long timeoutMillis) {
822 >    void sleep(long millis) {
823          try {
824 <            Thread.sleep(timeoutMillis);
825 <        } catch (InterruptedException wakeup) {}
824 >            delay(millis);
825 >        } catch (InterruptedException ie) {
826 >            AssertionFailedError afe =
827 >                new AssertionFailedError("Unexpected InterruptedException");
828 >            afe.initCause(ie);
829 >            throw afe;
830 >        }
831 >    }
832 >
833 >    /**
834 >     * Spin-waits up to the specified number of milliseconds for the given
835 >     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
836 >     */
837 >    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
838 >        long startTime = System.nanoTime();
839 >        for (;;) {
840 >            Thread.State s = thread.getState();
841 >            if (s == Thread.State.BLOCKED ||
842 >                s == Thread.State.WAITING ||
843 >                s == Thread.State.TIMED_WAITING)
844 >                return;
845 >            else if (s == Thread.State.TERMINATED)
846 >                fail("Unexpected thread termination");
847 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
848 >                threadAssertTrue(thread.isAlive());
849 >                return;
850 >            }
851 >            Thread.yield();
852 >        }
853 >    }
854 >
855 >    /**
856 >     * Waits up to LONG_DELAY_MS for the given thread to enter a wait
857 >     * state: BLOCKED, WAITING, or TIMED_WAITING.
858 >     */
859 >    void waitForThreadToEnterWaitState(Thread thread) {
860 >        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
861 >    }
862 >
863 >    /**
864 >     * Returns the number of milliseconds since time given by
865 >     * startNanoTime, which must have been previously returned from a
866 >     * call to {@link System.nanoTime()}.
867 >     */
868 >    long millisElapsedSince(long startNanoTime) {
869 >        return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
870      }
871  
872      /**
873 <     * Returns a new started Thread running the given runnable.
873 >     * Returns a new started daemon Thread running the given runnable.
874       */
875      Thread newStartedThread(Runnable runnable) {
876          Thread t = new Thread(runnable);
877 +        t.setDaemon(true);
878          t.start();
879          return t;
880      }
881  
882 +    /**
883 +     * Waits for the specified time (in milliseconds) for the thread
884 +     * to terminate (using {@link Thread#join(long)}), else interrupts
885 +     * the thread (in the hope that it may terminate later) and fails.
886 +     */
887 +    void awaitTermination(Thread t, long timeoutMillis) {
888 +        try {
889 +            t.join(timeoutMillis);
890 +        } catch (InterruptedException ie) {
891 +            threadUnexpectedException(ie);
892 +        } finally {
893 +            if (t.getState() != Thread.State.TERMINATED) {
894 +                t.interrupt();
895 +                fail("Test timed out");
896 +            }
897 +        }
898 +    }
899 +
900 +    /**
901 +     * Waits for LONG_DELAY_MS milliseconds for the thread to
902 +     * terminate (using {@link Thread#join(long)}), else interrupts
903 +     * the thread (in the hope that it may terminate later) and fails.
904 +     */
905 +    void awaitTermination(Thread t) {
906 +        awaitTermination(t, LONG_DELAY_MS);
907 +    }
908 +
909      // Some convenient Runnable classes
910  
911      public abstract class CheckedRunnable implements Runnable {
# Line 574 | Line 968 | public class JSR166TestCase extends Test
968                  realRun();
969                  threadShouldThrow("InterruptedException");
970              } catch (InterruptedException success) {
971 +                threadAssertFalse(Thread.interrupted());
972              } catch (Throwable t) {
973                  threadUnexpectedException(t);
974              }
# Line 588 | Line 983 | public class JSR166TestCase extends Test
983                  return realCall();
984              } catch (Throwable t) {
985                  threadUnexpectedException(t);
986 +                return null;
987              }
592            return null;
988          }
989      }
990  
991 <    public abstract class CheckedInterruptedCallable<T> implements Callable<T> {
991 >    public abstract class CheckedInterruptedCallable<T>
992 >        implements Callable<T> {
993          protected abstract T realCall() throws Throwable;
994  
995          public final T call() {
# Line 602 | Line 998 | public class JSR166TestCase extends Test
998                  threadShouldThrow("InterruptedException");
999                  return result;
1000              } catch (InterruptedException success) {
1001 +                threadAssertFalse(Thread.interrupted());
1002              } catch (Throwable t) {
1003                  threadUnexpectedException(t);
1004              }
# Line 625 | Line 1022 | public class JSR166TestCase extends Test
1022  
1023      public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
1024          return new CheckedCallable<String>() {
1025 <            public String realCall() {
1025 >            protected String realCall() {
1026                  try {
1027                      latch.await();
1028                  } catch (InterruptedException quittingTime) {}
# Line 633 | Line 1030 | public class JSR166TestCase extends Test
1030              }};
1031      }
1032  
1033 +    public Runnable awaiter(final CountDownLatch latch) {
1034 +        return new CheckedRunnable() {
1035 +            public void realRun() throws InterruptedException {
1036 +                await(latch);
1037 +            }};
1038 +    }
1039 +
1040 +    public void await(CountDownLatch latch) {
1041 +        try {
1042 +            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1043 +        } catch (Throwable t) {
1044 +            threadUnexpectedException(t);
1045 +        }
1046 +    }
1047 +
1048 +    public void await(Semaphore semaphore) {
1049 +        try {
1050 +            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1051 +        } catch (Throwable t) {
1052 +            threadUnexpectedException(t);
1053 +        }
1054 +    }
1055 +
1056 + //     /**
1057 + //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1058 + //      */
1059 + //     public void await(AtomicBoolean flag) {
1060 + //         await(flag, LONG_DELAY_MS);
1061 + //     }
1062 +
1063 + //     /**
1064 + //      * Spin-waits up to the specified timeout until flag becomes true.
1065 + //      */
1066 + //     public void await(AtomicBoolean flag, long timeoutMillis) {
1067 + //         long startTime = System.nanoTime();
1068 + //         while (!flag.get()) {
1069 + //             if (millisElapsedSince(startTime) > timeoutMillis)
1070 + //                 throw new AssertionFailedError("timed out");
1071 + //             Thread.yield();
1072 + //         }
1073 + //     }
1074 +
1075      public static class NPETask implements Callable<String> {
1076          public String call() { throw new NullPointerException(); }
1077      }
# Line 643 | Line 1082 | public class JSR166TestCase extends Test
1082  
1083      public class ShortRunnable extends CheckedRunnable {
1084          protected void realRun() throws Throwable {
1085 <            Thread.sleep(SHORT_DELAY_MS);
1085 >            delay(SHORT_DELAY_MS);
1086          }
1087      }
1088  
1089      public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1090          protected void realRun() throws InterruptedException {
1091 <            Thread.sleep(SHORT_DELAY_MS);
1091 >            delay(SHORT_DELAY_MS);
1092          }
1093      }
1094  
1095      public class SmallRunnable extends CheckedRunnable {
1096          protected void realRun() throws Throwable {
1097 <            Thread.sleep(SMALL_DELAY_MS);
1097 >            delay(SMALL_DELAY_MS);
1098          }
1099      }
1100  
1101      public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1102          protected void realRun() {
1103              try {
1104 <                Thread.sleep(SMALL_DELAY_MS);
1104 >                delay(SMALL_DELAY_MS);
1105              } catch (InterruptedException ok) {}
1106          }
1107      }
1108  
1109      public class SmallCallable extends CheckedCallable {
1110          protected Object realCall() throws InterruptedException {
1111 <            Thread.sleep(SMALL_DELAY_MS);
1111 >            delay(SMALL_DELAY_MS);
1112              return Boolean.TRUE;
1113          }
1114      }
1115  
677    public class SmallInterruptedRunnable extends CheckedInterruptedRunnable {
678        protected void realRun() throws InterruptedException {
679            Thread.sleep(SMALL_DELAY_MS);
680        }
681    }
682
1116      public class MediumRunnable extends CheckedRunnable {
1117          protected void realRun() throws Throwable {
1118 <            Thread.sleep(MEDIUM_DELAY_MS);
1118 >            delay(MEDIUM_DELAY_MS);
1119          }
1120      }
1121  
1122      public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1123          protected void realRun() throws InterruptedException {
1124 <            Thread.sleep(MEDIUM_DELAY_MS);
1124 >            delay(MEDIUM_DELAY_MS);
1125          }
1126      }
1127  
1128 +    public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1129 +        return new CheckedRunnable() {
1130 +            protected void realRun() {
1131 +                try {
1132 +                    delay(timeoutMillis);
1133 +                } catch (InterruptedException ok) {}
1134 +            }};
1135 +    }
1136 +
1137      public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1138          protected void realRun() {
1139              try {
1140 <                Thread.sleep(MEDIUM_DELAY_MS);
1140 >                delay(MEDIUM_DELAY_MS);
1141              } catch (InterruptedException ok) {}
1142          }
1143      }
# Line 703 | Line 1145 | public class JSR166TestCase extends Test
1145      public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1146          protected void realRun() {
1147              try {
1148 <                Thread.sleep(LONG_DELAY_MS);
1148 >                delay(LONG_DELAY_MS);
1149              } catch (InterruptedException ok) {}
1150          }
1151      }
# Line 717 | Line 1159 | public class JSR166TestCase extends Test
1159          }
1160      }
1161  
1162 +    public interface TrackedRunnable extends Runnable {
1163 +        boolean isDone();
1164 +    }
1165 +
1166 +    public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
1167 +        return new TrackedRunnable() {
1168 +                private volatile boolean done = false;
1169 +                public boolean isDone() { return done; }
1170 +                public void run() {
1171 +                    try {
1172 +                        delay(timeoutMillis);
1173 +                        done = true;
1174 +                    } catch (InterruptedException ok) {}
1175 +                }
1176 +            };
1177 +    }
1178 +
1179      public static class TrackedShortRunnable implements Runnable {
1180          public volatile boolean done = false;
1181          public void run() {
1182              try {
1183 <                Thread.sleep(SMALL_DELAY_MS);
1183 >                delay(SHORT_DELAY_MS);
1184 >                done = true;
1185 >            } catch (InterruptedException ok) {}
1186 >        }
1187 >    }
1188 >
1189 >    public static class TrackedSmallRunnable implements Runnable {
1190 >        public volatile boolean done = false;
1191 >        public void run() {
1192 >            try {
1193 >                delay(SMALL_DELAY_MS);
1194                  done = true;
1195              } catch (InterruptedException ok) {}
1196          }
# Line 731 | Line 1200 | public class JSR166TestCase extends Test
1200          public volatile boolean done = false;
1201          public void run() {
1202              try {
1203 <                Thread.sleep(MEDIUM_DELAY_MS);
1203 >                delay(MEDIUM_DELAY_MS);
1204                  done = true;
1205              } catch (InterruptedException ok) {}
1206          }
# Line 741 | Line 1210 | public class JSR166TestCase extends Test
1210          public volatile boolean done = false;
1211          public void run() {
1212              try {
1213 <                Thread.sleep(LONG_DELAY_MS);
1213 >                delay(LONG_DELAY_MS);
1214                  done = true;
1215              } catch (InterruptedException ok) {}
1216          }
# Line 758 | Line 1227 | public class JSR166TestCase extends Test
1227          public volatile boolean done = false;
1228          public Object call() {
1229              try {
1230 <                Thread.sleep(SMALL_DELAY_MS);
1230 >                delay(SMALL_DELAY_MS);
1231                  done = true;
1232              } catch (InterruptedException ok) {}
1233              return Boolean.TRUE;
1234          }
1235      }
1236  
1237 +    /**
1238 +     * Analog of CheckedRunnable for RecursiveAction
1239 +     */
1240 +    public abstract class CheckedRecursiveAction extends RecursiveAction {
1241 +        protected abstract void realCompute() throws Throwable;
1242 +
1243 +        @Override protected final void compute() {
1244 +            try {
1245 +                realCompute();
1246 +            } catch (Throwable t) {
1247 +                threadUnexpectedException(t);
1248 +            }
1249 +        }
1250 +    }
1251 +
1252 +    /**
1253 +     * Analog of CheckedCallable for RecursiveTask
1254 +     */
1255 +    public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1256 +        protected abstract T realCompute() throws Throwable;
1257 +
1258 +        @Override protected final T compute() {
1259 +            try {
1260 +                return realCompute();
1261 +            } catch (Throwable t) {
1262 +                threadUnexpectedException(t);
1263 +                return null;
1264 +            }
1265 +        }
1266 +    }
1267  
1268      /**
1269       * For use as RejectedExecutionHandler in constructors
# Line 774 | Line 1273 | public class JSR166TestCase extends Test
1273                                        ThreadPoolExecutor executor) {}
1274      }
1275  
1276 +    /**
1277 +     * A CyclicBarrier that uses timed await and fails with
1278 +     * AssertionFailedErrors instead of throwing checked exceptions.
1279 +     */
1280 +    public class CheckedBarrier extends CyclicBarrier {
1281 +        public CheckedBarrier(int parties) { super(parties); }
1282 +
1283 +        public int await() {
1284 +            try {
1285 +                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1286 +            } catch (TimeoutException e) {
1287 +                throw new AssertionFailedError("timed out");
1288 +            } catch (Exception e) {
1289 +                AssertionFailedError afe =
1290 +                    new AssertionFailedError("Unexpected exception: " + e);
1291 +                afe.initCause(e);
1292 +                throw afe;
1293 +            }
1294 +        }
1295 +    }
1296 +
1297 +    void checkEmpty(BlockingQueue q) {
1298 +        try {
1299 +            assertTrue(q.isEmpty());
1300 +            assertEquals(0, q.size());
1301 +            assertNull(q.peek());
1302 +            assertNull(q.poll());
1303 +            assertNull(q.poll(0, MILLISECONDS));
1304 +            assertEquals(q.toString(), "[]");
1305 +            assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1306 +            assertFalse(q.iterator().hasNext());
1307 +            try {
1308 +                q.element();
1309 +                shouldThrow();
1310 +            } catch (NoSuchElementException success) {}
1311 +            try {
1312 +                q.iterator().next();
1313 +                shouldThrow();
1314 +            } catch (NoSuchElementException success) {}
1315 +            try {
1316 +                q.remove();
1317 +                shouldThrow();
1318 +            } catch (NoSuchElementException success) {}
1319 +        } catch (InterruptedException ie) {
1320 +            threadUnexpectedException(ie);
1321 +        }
1322 +    }
1323 +
1324 +    void assertSerialEquals(Object x, Object y) {
1325 +        assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1326 +    }
1327 +
1328 +    void assertNotSerialEquals(Object x, Object y) {
1329 +        assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1330 +    }
1331 +
1332 +    byte[] serialBytes(Object o) {
1333 +        try {
1334 +            ByteArrayOutputStream bos = new ByteArrayOutputStream();
1335 +            ObjectOutputStream oos = new ObjectOutputStream(bos);
1336 +            oos.writeObject(o);
1337 +            oos.flush();
1338 +            oos.close();
1339 +            return bos.toByteArray();
1340 +        } catch (Throwable t) {
1341 +            threadUnexpectedException(t);
1342 +            return new byte[0];
1343 +        }
1344 +    }
1345 +
1346 +    @SuppressWarnings("unchecked")
1347 +    <T> T serialClone(T o) {
1348 +        try {
1349 +            ObjectInputStream ois = new ObjectInputStream
1350 +                (new ByteArrayInputStream(serialBytes(o)));
1351 +            T clone = (T) ois.readObject();
1352 +            assertSame(o.getClass(), clone.getClass());
1353 +            return clone;
1354 +        } catch (Throwable t) {
1355 +            threadUnexpectedException(t);
1356 +            return null;
1357 +        }
1358 +    }
1359 +
1360 +    public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1361 +                             Runnable... throwingActions) {
1362 +        for (Runnable throwingAction : throwingActions) {
1363 +            boolean threw = false;
1364 +            try { throwingAction.run(); }
1365 +            catch (Throwable t) {
1366 +                threw = true;
1367 +                if (!expectedExceptionClass.isInstance(t)) {
1368 +                    AssertionFailedError afe =
1369 +                        new AssertionFailedError
1370 +                        ("Expected " + expectedExceptionClass.getName() +
1371 +                         ", got " + t.getClass().getName());
1372 +                    afe.initCause(t);
1373 +                    threadUnexpectedException(afe);
1374 +                }
1375 +            }
1376 +            if (!threw)
1377 +                shouldThrow(expectedExceptionClass.getName());
1378 +        }
1379 +    }
1380   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines