ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.95
Committed: Mon Jan 21 19:43:52 2013 UTC (11 years, 3 months ago) by jsr166
Branch: MAIN
Changes since 1.94: +10 -0 lines
Log Message:
add printAllStackTraces debugging tool

File Contents

# User Rev Content
1 dl 1.1 /*
2 dl 1.13 * 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 jsr166 1.74 * http://creativecommons.org/publicdomain/zero/1.0/
5 jsr166 1.27 * Other contributors include Andrew Wright, Jeffrey Hayes,
6     * Pat Fisher, Mike Judd.
7 dl 1.1 */
8    
9     import junit.framework.*;
10 jsr166 1.79 import java.io.ByteArrayInputStream;
11     import java.io.ByteArrayOutputStream;
12     import java.io.ObjectInputStream;
13     import java.io.ObjectOutputStream;
14 jsr166 1.93 import java.util.ArrayList;
15 jsr166 1.72 import java.util.Arrays;
16 jsr166 1.81 import java.util.Date;
17 jsr166 1.93 import java.util.Enumeration;
18     import java.util.List;
19 jsr166 1.72 import java.util.NoSuchElementException;
20 jsr166 1.53 import java.util.PropertyPermission;
21 dl 1.1 import java.util.concurrent.*;
22 jsr166 1.81 import java.util.concurrent.atomic.AtomicBoolean;
23 jsr166 1.53 import java.util.concurrent.atomic.AtomicReference;
24 jsr166 1.36 import static java.util.concurrent.TimeUnit.MILLISECONDS;
25 jsr166 1.66 import static java.util.concurrent.TimeUnit.NANOSECONDS;
26 jsr166 1.53 import java.security.CodeSource;
27     import java.security.Permission;
28     import java.security.PermissionCollection;
29     import java.security.Permissions;
30     import java.security.Policy;
31     import java.security.ProtectionDomain;
32     import java.security.SecurityPermission;
33 dl 1.1
34     /**
35 dl 1.5 * Base class for JSR166 Junit TCK tests. Defines some constants,
36     * utility methods and classes, as well as a simple framework for
37     * helping to make sure that assertions failing in generated threads
38     * cause the associated test that generated them to itself fail (which
39 jsr166 1.27 * JUnit does not otherwise arrange). The rules for creating such
40 dl 1.5 * tests are:
41 dl 1.1 *
42     * <ol>
43     *
44     * <li> All assertions in code running in generated threads must use
45 jsr166 1.27 * the forms {@link #threadFail}, {@link #threadAssertTrue}, {@link
46 dl 1.18 * #threadAssertEquals}, or {@link #threadAssertNull}, (not
47 jsr166 1.50 * {@code fail}, {@code assertTrue}, etc.) It is OK (but not
48 dl 1.1 * particularly recommended) for other code to use these forms too.
49     * Only the most typically used JUnit assertion methods are defined
50     * this way, but enough to live with.</li>
51     *
52 dl 1.18 * <li> If you override {@link #setUp} or {@link #tearDown}, make sure
53 jsr166 1.50 * to invoke {@code super.setUp} and {@code super.tearDown} within
54 dl 1.1 * them. These methods are used to clear and check for thread
55     * assertion failures.</li>
56     *
57 jsr166 1.51 * <li>All delays and timeouts must use one of the constants {@code
58 jsr166 1.50 * SHORT_DELAY_MS}, {@code SMALL_DELAY_MS}, {@code MEDIUM_DELAY_MS},
59     * {@code LONG_DELAY_MS}. The idea here is that a SHORT is always
60 dl 1.5 * discriminable from zero time, and always allows enough time for the
61     * small amounts of computation (creating a thread, calling a few
62 dl 1.1 * methods, etc) needed to reach a timeout point. Similarly, a SMALL
63     * is always discriminable as larger than SHORT and smaller than
64     * MEDIUM. And so on. These constants are set to conservative values,
65 dl 1.2 * but even so, if there is ever any doubt, they can all be increased
66 jsr166 1.27 * in one spot to rerun tests on slower platforms.</li>
67 dl 1.1 *
68     * <li> All threads generated must be joined inside each test case
69 jsr166 1.50 * method (or {@code fail} to do so) before returning from the
70     * method. The {@code joinPool} method can be used to do this when
71 dl 1.1 * using Executors.</li>
72     *
73     * </ol>
74 dl 1.6 *
75 jsr166 1.92 * <p><b>Other notes</b>
76 dl 1.6 * <ul>
77     *
78     * <li> Usually, there is one testcase method per JSR166 method
79     * covering "normal" operation, and then as many exception-testing
80     * methods as there are exceptions the method can throw. Sometimes
81     * there are multiple tests per JSR166 method when the different
82     * "normal" behaviors differ significantly. And sometimes testcases
83     * cover multiple methods when they cannot be tested in
84     * isolation.</li>
85 jsr166 1.27 *
86 dl 1.6 * <li> The documentation style for testcases is to provide as javadoc
87     * a simple sentence or two describing the property that the testcase
88     * method purports to test. The javadocs do not say anything about how
89     * the property is tested. To find out, read the code.</li>
90     *
91     * <li> These tests are "conformance tests", and do not attempt to
92     * test throughput, latency, scalability or other performance factors
93     * (see the separate "jtreg" tests for a set intended to check these
94     * for the most central aspects of functionality.) So, most tests use
95     * the smallest sensible numbers of threads, collection sizes, etc
96     * needed to check basic conformance.</li>
97     *
98     * <li>The test classes currently do not declare inclusion in
99     * any particular package to simplify things for people integrating
100     * them in TCK test suites.</li>
101     *
102 jsr166 1.50 * <li> As a convenience, the {@code main} of this class (JSR166TestCase)
103 dl 1.6 * runs all JSR166 unit tests.</li>
104     *
105     * </ul>
106 dl 1.1 */
107     public class JSR166TestCase extends TestCase {
108 jsr166 1.49 private static final boolean useSecurityManager =
109     Boolean.getBoolean("jsr166.useSecurityManager");
110    
111 jsr166 1.62 protected static final boolean expensiveTests =
112     Boolean.getBoolean("jsr166.expensiveTests");
113    
114 dl 1.6 /**
115 jsr166 1.61 * If true, report on stdout all "slow" tests, that is, ones that
116     * take more than profileThreshold milliseconds to execute.
117     */
118     private static final boolean profileTests =
119     Boolean.getBoolean("jsr166.profileTests");
120    
121     /**
122     * The number of milliseconds that tests are permitted for
123     * execution without being reported, when profileTests is set.
124     */
125     private static final long profileThreshold =
126     Long.getLong("jsr166.profileThreshold", 100);
127    
128     protected void runTest() throws Throwable {
129     if (profileTests)
130     runTestProfiled();
131     else
132     super.runTest();
133     }
134    
135     protected void runTestProfiled() throws Throwable {
136     long t0 = System.nanoTime();
137     try {
138     super.runTest();
139     } finally {
140     long elapsedMillis =
141     (System.nanoTime() - t0) / (1000L * 1000L);
142     if (elapsedMillis >= profileThreshold)
143     System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
144     }
145     }
146 jsr166 1.63
147 jsr166 1.61 /**
148 jsr166 1.94 * Runs all JSR166 unit tests using junit.textui.TestRunner.
149     * Optional command line arg provides the number of iterations to
150     * repeat running the tests.
151 jsr166 1.27 */
152 jsr166 1.41 public static void main(String[] args) {
153 jsr166 1.49 if (useSecurityManager) {
154     System.err.println("Setting a permissive security manager");
155     Policy.setPolicy(permissivePolicy());
156     System.setSecurityManager(new SecurityManager());
157     }
158 jsr166 1.56 int iters = (args.length == 0) ? 1 : Integer.parseInt(args[0]);
159    
160 dl 1.16 Test s = suite();
161 dl 1.22 for (int i = 0; i < iters; ++i) {
162 jsr166 1.41 junit.textui.TestRunner.run(s);
163 dl 1.22 System.gc();
164     System.runFinalization();
165     }
166     System.exit(0);
167 dl 1.6 }
168    
169 jsr166 1.60 public static TestSuite newTestSuite(Object... suiteOrClasses) {
170     TestSuite suite = new TestSuite();
171     for (Object suiteOrClass : suiteOrClasses) {
172     if (suiteOrClass instanceof TestSuite)
173     suite.addTest((TestSuite) suiteOrClass);
174     else if (suiteOrClass instanceof Class)
175     suite.addTest(new TestSuite((Class<?>) suiteOrClass));
176     else
177     throw new ClassCastException("not a test suite or class");
178     }
179     return suite;
180     }
181    
182 dl 1.6 /**
183 jsr166 1.60 * Collects all JSR166 unit tests as one suite.
184 jsr166 1.27 */
185 jsr166 1.41 public static Test suite() {
186 jsr166 1.60 return newTestSuite(
187     ForkJoinPoolTest.suite(),
188     ForkJoinTaskTest.suite(),
189     RecursiveActionTest.suite(),
190     RecursiveTaskTest.suite(),
191     LinkedTransferQueueTest.suite(),
192     PhaserTest.suite(),
193     ThreadLocalRandomTest.suite(),
194     AbstractExecutorServiceTest.suite(),
195     AbstractQueueTest.suite(),
196     AbstractQueuedSynchronizerTest.suite(),
197     AbstractQueuedLongSynchronizerTest.suite(),
198     ArrayBlockingQueueTest.suite(),
199     ArrayDequeTest.suite(),
200     AtomicBooleanTest.suite(),
201     AtomicIntegerArrayTest.suite(),
202     AtomicIntegerFieldUpdaterTest.suite(),
203     AtomicIntegerTest.suite(),
204     AtomicLongArrayTest.suite(),
205     AtomicLongFieldUpdaterTest.suite(),
206     AtomicLongTest.suite(),
207     AtomicMarkableReferenceTest.suite(),
208     AtomicReferenceArrayTest.suite(),
209     AtomicReferenceFieldUpdaterTest.suite(),
210     AtomicReferenceTest.suite(),
211     AtomicStampedReferenceTest.suite(),
212     ConcurrentHashMapTest.suite(),
213     ConcurrentLinkedDequeTest.suite(),
214     ConcurrentLinkedQueueTest.suite(),
215     ConcurrentSkipListMapTest.suite(),
216     ConcurrentSkipListSubMapTest.suite(),
217     ConcurrentSkipListSetTest.suite(),
218     ConcurrentSkipListSubSetTest.suite(),
219     CopyOnWriteArrayListTest.suite(),
220     CopyOnWriteArraySetTest.suite(),
221     CountDownLatchTest.suite(),
222     CyclicBarrierTest.suite(),
223     DelayQueueTest.suite(),
224     EntryTest.suite(),
225     ExchangerTest.suite(),
226     ExecutorsTest.suite(),
227     ExecutorCompletionServiceTest.suite(),
228     FutureTaskTest.suite(),
229     LinkedBlockingDequeTest.suite(),
230     LinkedBlockingQueueTest.suite(),
231     LinkedListTest.suite(),
232     LockSupportTest.suite(),
233     PriorityBlockingQueueTest.suite(),
234     PriorityQueueTest.suite(),
235     ReentrantLockTest.suite(),
236     ReentrantReadWriteLockTest.suite(),
237     ScheduledExecutorTest.suite(),
238     ScheduledExecutorSubclassTest.suite(),
239     SemaphoreTest.suite(),
240     SynchronousQueueTest.suite(),
241     SystemTest.suite(),
242     ThreadLocalTest.suite(),
243     ThreadPoolExecutorTest.suite(),
244     ThreadPoolExecutorSubclassTest.suite(),
245     ThreadTest.suite(),
246     TimeUnitTest.suite(),
247     TreeMapTest.suite(),
248     TreeSetTest.suite(),
249     TreeSubMapTest.suite(),
250     TreeSubSetTest.suite());
251 dl 1.6 }
252    
253 dl 1.1
254 dl 1.2 public static long SHORT_DELAY_MS;
255     public static long SMALL_DELAY_MS;
256     public static long MEDIUM_DELAY_MS;
257     public static long LONG_DELAY_MS;
258    
259    
260     /**
261 jsr166 1.27 * Returns the shortest timed delay. This could
262 dl 1.15 * be reimplemented to use for example a Property.
263 jsr166 1.27 */
264 dl 1.2 protected long getShortDelay() {
265 dl 1.21 return 50;
266 dl 1.2 }
267    
268     /**
269 jsr166 1.27 * Sets delays as multiples of SHORT_DELAY.
270 dl 1.2 */
271 jsr166 1.43 protected void setDelays() {
272 dl 1.2 SHORT_DELAY_MS = getShortDelay();
273 jsr166 1.53 SMALL_DELAY_MS = SHORT_DELAY_MS * 5;
274 dl 1.2 MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
275 jsr166 1.71 LONG_DELAY_MS = SHORT_DELAY_MS * 200;
276 dl 1.2 }
277    
278 dl 1.1 /**
279 jsr166 1.81 * Returns a timeout in milliseconds to be used in tests that
280     * verify that operations block or time out.
281     */
282     long timeoutMillis() {
283     return SHORT_DELAY_MS / 4;
284     }
285    
286     /**
287     * Returns a new Date instance representing a time delayMillis
288     * milliseconds in the future.
289     */
290     Date delayedDate(long delayMillis) {
291 jsr166 1.84 return new Date(System.currentTimeMillis() + delayMillis);
292 jsr166 1.81 }
293    
294     /**
295 jsr166 1.53 * The first exception encountered if any threadAssertXXX method fails.
296 dl 1.1 */
297 jsr166 1.53 private final AtomicReference<Throwable> threadFailure
298     = new AtomicReference<Throwable>(null);
299 dl 1.1
300     /**
301 jsr166 1.53 * Records an exception so that it can be rethrown later in the test
302     * harness thread, triggering a test case failure. Only the first
303     * failure is recorded; subsequent calls to this method from within
304     * the same test have no effect.
305 dl 1.1 */
306 jsr166 1.53 public void threadRecordFailure(Throwable t) {
307     threadFailure.compareAndSet(null, t);
308     }
309    
310 jsr166 1.27 public void setUp() {
311 dl 1.2 setDelays();
312 dl 1.1 }
313    
314     /**
315 jsr166 1.85 * Extra checks that get done for all test cases.
316     *
317 jsr166 1.53 * Triggers test case failure if any thread assertions have failed,
318     * by rethrowing, in the test harness thread, any exception recorded
319     * earlier by threadRecordFailure.
320 jsr166 1.85 *
321     * Triggers test case failure if interrupt status is set in the main thread.
322 jsr166 1.53 */
323     public void tearDown() throws Exception {
324 jsr166 1.70 Throwable t = threadFailure.getAndSet(null);
325 jsr166 1.53 if (t != null) {
326     if (t instanceof Error)
327     throw (Error) t;
328     else if (t instanceof RuntimeException)
329     throw (RuntimeException) t;
330     else if (t instanceof Exception)
331     throw (Exception) t;
332 jsr166 1.57 else {
333     AssertionFailedError afe =
334     new AssertionFailedError(t.toString());
335     afe.initCause(t);
336     throw afe;
337     }
338 jsr166 1.53 }
339 jsr166 1.85
340     if (Thread.interrupted())
341     throw new AssertionFailedError("interrupt status set in main thread");
342 dl 1.1 }
343    
344 dl 1.5 /**
345 jsr166 1.53 * Just like fail(reason), but additionally recording (using
346 jsr166 1.57 * threadRecordFailure) any AssertionFailedError thrown, so that
347     * the current testcase will fail.
348 jsr166 1.27 */
349 dl 1.1 public void threadFail(String reason) {
350 jsr166 1.53 try {
351     fail(reason);
352 jsr166 1.57 } catch (AssertionFailedError t) {
353 jsr166 1.53 threadRecordFailure(t);
354     fail(reason);
355     }
356 dl 1.1 }
357    
358 dl 1.5 /**
359 jsr166 1.53 * Just like assertTrue(b), but additionally recording (using
360 jsr166 1.57 * threadRecordFailure) any AssertionFailedError thrown, so that
361     * the current testcase will fail.
362 jsr166 1.27 */
363 dl 1.1 public void threadAssertTrue(boolean b) {
364 jsr166 1.53 try {
365 dl 1.1 assertTrue(b);
366 jsr166 1.57 } catch (AssertionFailedError t) {
367 jsr166 1.53 threadRecordFailure(t);
368     throw t;
369 dl 1.1 }
370     }
371 dl 1.5
372     /**
373 jsr166 1.53 * Just like assertFalse(b), but additionally recording (using
374 jsr166 1.57 * threadRecordFailure) any AssertionFailedError thrown, so that
375     * the current testcase will fail.
376 jsr166 1.27 */
377 dl 1.1 public void threadAssertFalse(boolean b) {
378 jsr166 1.53 try {
379 dl 1.1 assertFalse(b);
380 jsr166 1.57 } catch (AssertionFailedError t) {
381 jsr166 1.53 threadRecordFailure(t);
382     throw t;
383 dl 1.1 }
384     }
385 dl 1.5
386     /**
387 jsr166 1.53 * Just like assertNull(x), but additionally recording (using
388 jsr166 1.57 * threadRecordFailure) any AssertionFailedError thrown, so that
389     * the current testcase will fail.
390 jsr166 1.27 */
391 dl 1.1 public void threadAssertNull(Object x) {
392 jsr166 1.53 try {
393 dl 1.1 assertNull(x);
394 jsr166 1.57 } catch (AssertionFailedError t) {
395 jsr166 1.53 threadRecordFailure(t);
396     throw t;
397 dl 1.1 }
398     }
399 dl 1.5
400     /**
401 jsr166 1.53 * Just like assertEquals(x, y), but additionally recording (using
402 jsr166 1.57 * threadRecordFailure) any AssertionFailedError thrown, so that
403     * the current testcase will fail.
404 jsr166 1.27 */
405 dl 1.1 public void threadAssertEquals(long x, long y) {
406 jsr166 1.53 try {
407 dl 1.1 assertEquals(x, y);
408 jsr166 1.57 } catch (AssertionFailedError t) {
409 jsr166 1.53 threadRecordFailure(t);
410     throw t;
411 dl 1.1 }
412     }
413 dl 1.5
414     /**
415 jsr166 1.53 * Just like assertEquals(x, y), but additionally recording (using
416 jsr166 1.57 * threadRecordFailure) any AssertionFailedError thrown, so that
417     * the current testcase will fail.
418 jsr166 1.27 */
419 dl 1.1 public void threadAssertEquals(Object x, Object y) {
420 jsr166 1.53 try {
421 dl 1.1 assertEquals(x, y);
422 jsr166 1.57 } catch (AssertionFailedError t) {
423 jsr166 1.53 threadRecordFailure(t);
424     throw t;
425 jsr166 1.57 } catch (Throwable t) {
426     threadUnexpectedException(t);
427 dl 1.1 }
428     }
429    
430 dl 1.5 /**
431 jsr166 1.53 * Just like assertSame(x, y), but additionally recording (using
432 jsr166 1.57 * threadRecordFailure) any AssertionFailedError thrown, so that
433     * the current testcase will fail.
434 jsr166 1.52 */
435     public void threadAssertSame(Object x, Object y) {
436 jsr166 1.53 try {
437 jsr166 1.52 assertSame(x, y);
438 jsr166 1.57 } catch (AssertionFailedError t) {
439 jsr166 1.53 threadRecordFailure(t);
440     throw t;
441 jsr166 1.52 }
442     }
443    
444     /**
445 jsr166 1.53 * Calls threadFail with message "should throw exception".
446 jsr166 1.33 */
447 dl 1.3 public void threadShouldThrow() {
448 jsr166 1.53 threadFail("should throw exception");
449 dl 1.3 }
450    
451 dl 1.5 /**
452 jsr166 1.53 * Calls threadFail with message "should throw" + exceptionName.
453 jsr166 1.40 */
454     public void threadShouldThrow(String exceptionName) {
455 jsr166 1.53 threadFail("should throw " + exceptionName);
456 dl 1.3 }
457    
458 dl 1.31 /**
459 jsr166 1.57 * Records the given exception using {@link #threadRecordFailure},
460     * then rethrows the exception, wrapping it in an
461     * AssertionFailedError if necessary.
462 dl 1.31 */
463 jsr166 1.53 public void threadUnexpectedException(Throwable t) {
464     threadRecordFailure(t);
465     t.printStackTrace();
466     if (t instanceof RuntimeException)
467     throw (RuntimeException) t;
468     else if (t instanceof Error)
469     throw (Error) t;
470     else {
471 jsr166 1.57 AssertionFailedError afe =
472     new AssertionFailedError("unexpected exception: " + t);
473 jsr166 1.82 afe.initCause(t);
474 jsr166 1.57 throw afe;
475 jsr166 1.55 }
476 dl 1.31 }
477 dl 1.3
478 dl 1.1 /**
479 jsr166 1.81 * Delays, via Thread.sleep, for the given millisecond delay, but
480 dl 1.76 * if the sleep is shorter than specified, may re-sleep or yield
481     * until time elapses.
482     */
483 jsr166 1.81 static void delay(long millis) throws InterruptedException {
484 dl 1.76 long startTime = System.nanoTime();
485 jsr166 1.80 long ns = millis * 1000 * 1000;
486 dl 1.76 for (;;) {
487 jsr166 1.80 if (millis > 0L)
488     Thread.sleep(millis);
489 dl 1.76 else // too short to sleep
490     Thread.yield();
491     long d = ns - (System.nanoTime() - startTime);
492     if (d > 0L)
493 jsr166 1.80 millis = d / (1000 * 1000);
494 dl 1.76 else
495     break;
496     }
497     }
498    
499     /**
500 jsr166 1.53 * Waits out termination of a thread pool or fails doing so.
501 dl 1.1 */
502 jsr166 1.81 void joinPool(ExecutorService exec) {
503 dl 1.1 try {
504     exec.shutdown();
505 jsr166 1.54 assertTrue("ExecutorService did not terminate in a timely manner",
506 jsr166 1.71 exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS));
507 jsr166 1.33 } catch (SecurityException ok) {
508 dl 1.22 // Allowed in case test doesn't have privs
509 jsr166 1.33 } catch (InterruptedException ie) {
510 jsr166 1.44 fail("Unexpected InterruptedException");
511 dl 1.1 }
512     }
513    
514 jsr166 1.78 /**
515 jsr166 1.95 * A debugging tool to print all stack traces, as jstack does.
516     */
517     void printAllStackTraces() {
518     System.err.println(
519     Arrays.toString(
520     java.lang.management.ManagementFactory.getThreadMXBean()
521     .dumpAllThreads(true, true)));
522     }
523    
524     /**
525 jsr166 1.81 * Checks that thread does not terminate within the default
526     * millisecond delay of {@code timeoutMillis()}.
527     */
528     void assertThreadStaysAlive(Thread thread) {
529     assertThreadStaysAlive(thread, timeoutMillis());
530     }
531    
532     /**
533 jsr166 1.80 * Checks that thread does not terminate within the given millisecond delay.
534 jsr166 1.78 */
535 jsr166 1.81 void assertThreadStaysAlive(Thread thread, long millis) {
536 jsr166 1.78 try {
537 jsr166 1.80 // No need to optimize the failing case via Thread.join.
538     delay(millis);
539 jsr166 1.78 assertTrue(thread.isAlive());
540     } catch (InterruptedException ie) {
541     fail("Unexpected InterruptedException");
542     }
543     }
544 dl 1.5
545     /**
546 jsr166 1.90 * Checks that the threads do not terminate within the default
547     * millisecond delay of {@code timeoutMillis()}.
548     */
549     void assertThreadsStayAlive(Thread... threads) {
550     assertThreadsStayAlive(timeoutMillis(), threads);
551     }
552    
553     /**
554     * Checks that the threads do not terminate within the given millisecond delay.
555     */
556     void assertThreadsStayAlive(long millis, Thread... threads) {
557     try {
558     // No need to optimize the failing case via Thread.join.
559     delay(millis);
560     for (Thread thread : threads)
561     assertTrue(thread.isAlive());
562     } catch (InterruptedException ie) {
563     fail("Unexpected InterruptedException");
564     }
565     }
566    
567     /**
568 jsr166 1.83 * Checks that future.get times out, with the default timeout of
569     * {@code timeoutMillis()}.
570     */
571     void assertFutureTimesOut(Future future) {
572     assertFutureTimesOut(future, timeoutMillis());
573     }
574    
575     /**
576     * Checks that future.get times out, with the given millisecond timeout.
577     */
578     void assertFutureTimesOut(Future future, long timeoutMillis) {
579     long startTime = System.nanoTime();
580     try {
581     future.get(timeoutMillis, MILLISECONDS);
582     shouldThrow();
583     } catch (TimeoutException success) {
584     } catch (Exception e) {
585     threadUnexpectedException(e);
586     } finally { future.cancel(true); }
587     assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
588     }
589    
590     /**
591 jsr166 1.53 * Fails with message "should throw exception".
592 jsr166 1.27 */
593 dl 1.3 public void shouldThrow() {
594     fail("Should throw exception");
595     }
596    
597 dl 1.5 /**
598 jsr166 1.53 * Fails with message "should throw " + exceptionName.
599 jsr166 1.40 */
600     public void shouldThrow(String exceptionName) {
601     fail("Should throw " + exceptionName);
602     }
603    
604     /**
605 dl 1.1 * The number of elements to place in collections, arrays, etc.
606     */
607 jsr166 1.45 public static final int SIZE = 20;
608 dl 1.1
609     // Some convenient Integer constants
610    
611 jsr166 1.47 public static final Integer zero = new Integer(0);
612     public static final Integer one = new Integer(1);
613     public static final Integer two = new Integer(2);
614     public static final Integer three = new Integer(3);
615 jsr166 1.45 public static final Integer four = new Integer(4);
616     public static final Integer five = new Integer(5);
617 jsr166 1.47 public static final Integer six = new Integer(6);
618 jsr166 1.45 public static final Integer seven = new Integer(7);
619     public static final Integer eight = new Integer(8);
620 jsr166 1.47 public static final Integer nine = new Integer(9);
621 jsr166 1.45 public static final Integer m1 = new Integer(-1);
622     public static final Integer m2 = new Integer(-2);
623     public static final Integer m3 = new Integer(-3);
624 jsr166 1.47 public static final Integer m4 = new Integer(-4);
625     public static final Integer m5 = new Integer(-5);
626     public static final Integer m6 = new Integer(-6);
627 jsr166 1.45 public static final Integer m10 = new Integer(-10);
628 dl 1.7
629    
630     /**
631 jsr166 1.49 * Runs Runnable r with a security policy that permits precisely
632     * the specified permissions. If there is no current security
633     * manager, the runnable is run twice, both with and without a
634     * security manager. We require that any security manager permit
635     * getPolicy/setPolicy.
636     */
637     public void runWithPermissions(Runnable r, Permission... permissions) {
638     SecurityManager sm = System.getSecurityManager();
639     if (sm == null) {
640     r.run();
641 jsr166 1.93 }
642     runWithSecurityManagerWithPermissions(r, permissions);
643     }
644    
645     /**
646     * Runs Runnable r with a security policy that permits precisely
647     * the specified permissions. If there is no current security
648     * manager, a temporary one is set for the duration of the
649     * Runnable. We require that any security manager permit
650     * getPolicy/setPolicy.
651     */
652     public void runWithSecurityManagerWithPermissions(Runnable r,
653     Permission... permissions) {
654     SecurityManager sm = System.getSecurityManager();
655     if (sm == null) {
656 jsr166 1.49 Policy savedPolicy = Policy.getPolicy();
657     try {
658     Policy.setPolicy(permissivePolicy());
659     System.setSecurityManager(new SecurityManager());
660 jsr166 1.93 runWithSecurityManagerWithPermissions(r, permissions);
661 jsr166 1.49 } finally {
662     System.setSecurityManager(null);
663     Policy.setPolicy(savedPolicy);
664     }
665     } else {
666     Policy savedPolicy = Policy.getPolicy();
667     AdjustablePolicy policy = new AdjustablePolicy(permissions);
668     Policy.setPolicy(policy);
669    
670     try {
671     r.run();
672     } finally {
673     policy.addPermission(new SecurityPermission("setPolicy"));
674     Policy.setPolicy(savedPolicy);
675     }
676     }
677     }
678    
679     /**
680     * Runs a runnable without any permissions.
681     */
682     public void runWithoutPermissions(Runnable r) {
683     runWithPermissions(r);
684     }
685    
686     /**
687 dl 1.7 * A security policy where new permissions can be dynamically added
688     * or all cleared.
689     */
690 jsr166 1.45 public static class AdjustablePolicy extends java.security.Policy {
691 dl 1.7 Permissions perms = new Permissions();
692 jsr166 1.49 AdjustablePolicy(Permission... permissions) {
693     for (Permission permission : permissions)
694     perms.add(permission);
695     }
696 dl 1.7 void addPermission(Permission perm) { perms.add(perm); }
697     void clearPermissions() { perms = new Permissions(); }
698 jsr166 1.42 public PermissionCollection getPermissions(CodeSource cs) {
699     return perms;
700     }
701     public PermissionCollection getPermissions(ProtectionDomain pd) {
702     return perms;
703     }
704     public boolean implies(ProtectionDomain pd, Permission p) {
705     return perms.implies(p);
706     }
707     public void refresh() {}
708 jsr166 1.93 public String toString() {
709     List<Permission> ps = new ArrayList<Permission>();
710     for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
711     ps.add(e.nextElement());
712     return "AdjustablePolicy with permissions " + ps;
713     }
714 dl 1.7 }
715 dl 1.1
716 jsr166 1.38 /**
717 jsr166 1.49 * Returns a policy containing all the permissions we ever need.
718     */
719     public static Policy permissivePolicy() {
720     return new AdjustablePolicy
721     // Permissions j.u.c. needs directly
722     (new RuntimePermission("modifyThread"),
723     new RuntimePermission("getClassLoader"),
724     new RuntimePermission("setContextClassLoader"),
725     // Permissions needed to change permissions!
726     new SecurityPermission("getPolicy"),
727     new SecurityPermission("setPolicy"),
728     new RuntimePermission("setSecurityManager"),
729     // Permissions needed by the junit test harness
730     new RuntimePermission("accessDeclaredMembers"),
731     new PropertyPermission("*", "read"),
732     new java.io.FilePermission("<<ALL FILES>>", "read"));
733     }
734    
735     /**
736 jsr166 1.60 * Sleeps until the given time has elapsed.
737     * Throws AssertionFailedError if interrupted.
738     */
739     void sleep(long millis) {
740     try {
741 dl 1.76 delay(millis);
742 jsr166 1.60 } catch (InterruptedException ie) {
743     AssertionFailedError afe =
744     new AssertionFailedError("Unexpected InterruptedException");
745     afe.initCause(ie);
746     throw afe;
747     }
748     }
749    
750     /**
751 jsr166 1.88 * Spin-waits up to the specified number of milliseconds for the given
752 jsr166 1.65 * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
753     */
754     void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
755 jsr166 1.88 long startTime = System.nanoTime();
756 jsr166 1.65 for (;;) {
757     Thread.State s = thread.getState();
758     if (s == Thread.State.BLOCKED ||
759     s == Thread.State.WAITING ||
760 jsr166 1.67 s == Thread.State.TIMED_WAITING)
761 jsr166 1.65 return;
762 jsr166 1.67 else if (s == Thread.State.TERMINATED)
763     fail("Unexpected thread termination");
764 jsr166 1.88 else if (millisElapsedSince(startTime) > timeoutMillis) {
765 jsr166 1.67 threadAssertTrue(thread.isAlive());
766     return;
767     }
768 jsr166 1.65 Thread.yield();
769     }
770     }
771    
772     /**
773 jsr166 1.75 * Waits up to LONG_DELAY_MS for the given thread to enter a wait
774     * state: BLOCKED, WAITING, or TIMED_WAITING.
775     */
776     void waitForThreadToEnterWaitState(Thread thread) {
777     waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
778     }
779    
780     /**
781 jsr166 1.66 * Returns the number of milliseconds since time given by
782     * startNanoTime, which must have been previously returned from a
783     * call to {@link System.nanoTime()}.
784     */
785     long millisElapsedSince(long startNanoTime) {
786     return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
787     }
788 jsr166 1.68
789 jsr166 1.66 /**
790 jsr166 1.58 * Returns a new started daemon Thread running the given runnable.
791 jsr166 1.38 */
792     Thread newStartedThread(Runnable runnable) {
793     Thread t = new Thread(runnable);
794 jsr166 1.58 t.setDaemon(true);
795 jsr166 1.38 t.start();
796     return t;
797     }
798 dl 1.1
799 jsr166 1.59 /**
800     * Waits for the specified time (in milliseconds) for the thread
801     * to terminate (using {@link Thread#join(long)}), else interrupts
802     * the thread (in the hope that it may terminate later) and fails.
803     */
804     void awaitTermination(Thread t, long timeoutMillis) {
805     try {
806     t.join(timeoutMillis);
807     } catch (InterruptedException ie) {
808     threadUnexpectedException(ie);
809     } finally {
810 jsr166 1.83 if (t.getState() != Thread.State.TERMINATED) {
811 jsr166 1.59 t.interrupt();
812     fail("Test timed out");
813     }
814     }
815     }
816    
817 jsr166 1.75 /**
818     * Waits for LONG_DELAY_MS milliseconds for the thread to
819     * terminate (using {@link Thread#join(long)}), else interrupts
820     * the thread (in the hope that it may terminate later) and fails.
821     */
822     void awaitTermination(Thread t) {
823     awaitTermination(t, LONG_DELAY_MS);
824     }
825    
826 dl 1.1 // Some convenient Runnable classes
827    
828 jsr166 1.45 public abstract class CheckedRunnable implements Runnable {
829     protected abstract void realRun() throws Throwable;
830 jsr166 1.35
831     public final void run() {
832     try {
833     realRun();
834     } catch (Throwable t) {
835     threadUnexpectedException(t);
836     }
837     }
838     }
839    
840 jsr166 1.45 public abstract class RunnableShouldThrow implements Runnable {
841     protected abstract void realRun() throws Throwable;
842 jsr166 1.40
843     final Class<?> exceptionClass;
844    
845     <T extends Throwable> RunnableShouldThrow(Class<T> exceptionClass) {
846     this.exceptionClass = exceptionClass;
847     }
848    
849     public final void run() {
850     try {
851     realRun();
852     threadShouldThrow(exceptionClass.getSimpleName());
853     } catch (Throwable t) {
854     if (! exceptionClass.isInstance(t))
855     threadUnexpectedException(t);
856     }
857     }
858     }
859    
860 jsr166 1.45 public abstract class ThreadShouldThrow extends Thread {
861     protected abstract void realRun() throws Throwable;
862 jsr166 1.40
863     final Class<?> exceptionClass;
864    
865     <T extends Throwable> ThreadShouldThrow(Class<T> exceptionClass) {
866     this.exceptionClass = exceptionClass;
867     }
868    
869     public final void run() {
870     try {
871     realRun();
872     threadShouldThrow(exceptionClass.getSimpleName());
873     } catch (Throwable t) {
874     if (! exceptionClass.isInstance(t))
875     threadUnexpectedException(t);
876     }
877     }
878     }
879    
880 jsr166 1.45 public abstract class CheckedInterruptedRunnable implements Runnable {
881     protected abstract void realRun() throws Throwable;
882 jsr166 1.35
883     public final void run() {
884     try {
885     realRun();
886 jsr166 1.40 threadShouldThrow("InterruptedException");
887 jsr166 1.35 } catch (InterruptedException success) {
888 jsr166 1.81 threadAssertFalse(Thread.interrupted());
889 jsr166 1.35 } catch (Throwable t) {
890     threadUnexpectedException(t);
891     }
892     }
893     }
894    
895 jsr166 1.45 public abstract class CheckedCallable<T> implements Callable<T> {
896     protected abstract T realCall() throws Throwable;
897 jsr166 1.35
898     public final T call() {
899     try {
900     return realCall();
901     } catch (Throwable t) {
902     threadUnexpectedException(t);
903 jsr166 1.53 return null;
904 jsr166 1.35 }
905 jsr166 1.40 }
906     }
907    
908 jsr166 1.53 public abstract class CheckedInterruptedCallable<T>
909     implements Callable<T> {
910 jsr166 1.45 protected abstract T realCall() throws Throwable;
911 jsr166 1.40
912     public final T call() {
913     try {
914     T result = realCall();
915     threadShouldThrow("InterruptedException");
916     return result;
917     } catch (InterruptedException success) {
918 jsr166 1.81 threadAssertFalse(Thread.interrupted());
919 jsr166 1.40 } catch (Throwable t) {
920     threadUnexpectedException(t);
921     }
922     return null;
923 jsr166 1.35 }
924     }
925    
926 jsr166 1.45 public static class NoOpRunnable implements Runnable {
927 dl 1.1 public void run() {}
928     }
929    
930 jsr166 1.45 public static class NoOpCallable implements Callable {
931 dl 1.1 public Object call() { return Boolean.TRUE; }
932 dl 1.10 }
933    
934 jsr166 1.45 public static final String TEST_STRING = "a test string";
935 dl 1.10
936 jsr166 1.45 public static class StringTask implements Callable<String> {
937 dl 1.10 public String call() { return TEST_STRING; }
938     }
939    
940 jsr166 1.48 public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
941     return new CheckedCallable<String>() {
942 jsr166 1.64 protected String realCall() {
943 jsr166 1.48 try {
944     latch.await();
945     } catch (InterruptedException quittingTime) {}
946     return TEST_STRING;
947     }};
948     }
949    
950 jsr166 1.73 public Runnable awaiter(final CountDownLatch latch) {
951     return new CheckedRunnable() {
952     public void realRun() throws InterruptedException {
953 jsr166 1.79 await(latch);
954 jsr166 1.73 }};
955     }
956    
957 jsr166 1.79 public void await(CountDownLatch latch) {
958     try {
959     assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
960     } catch (Throwable t) {
961     threadUnexpectedException(t);
962     }
963     }
964    
965 jsr166 1.89 public void await(Semaphore semaphore) {
966     try {
967     assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
968     } catch (Throwable t) {
969     threadUnexpectedException(t);
970     }
971     }
972    
973 jsr166 1.81 // /**
974     // * Spin-waits up to LONG_DELAY_MS until flag becomes true.
975     // */
976     // public void await(AtomicBoolean flag) {
977     // await(flag, LONG_DELAY_MS);
978     // }
979    
980     // /**
981     // * Spin-waits up to the specified timeout until flag becomes true.
982     // */
983     // public void await(AtomicBoolean flag, long timeoutMillis) {
984     // long startTime = System.nanoTime();
985     // while (!flag.get()) {
986     // if (millisElapsedSince(startTime) > timeoutMillis)
987     // throw new AssertionFailedError("timed out");
988     // Thread.yield();
989     // }
990     // }
991    
992 jsr166 1.45 public static class NPETask implements Callable<String> {
993 dl 1.10 public String call() { throw new NullPointerException(); }
994     }
995    
996 jsr166 1.45 public static class CallableOne implements Callable<Integer> {
997 dl 1.10 public Integer call() { return one; }
998 dl 1.1 }
999    
1000 jsr166 1.45 public class ShortRunnable extends CheckedRunnable {
1001     protected void realRun() throws Throwable {
1002 dl 1.76 delay(SHORT_DELAY_MS);
1003 dl 1.1 }
1004     }
1005    
1006 jsr166 1.45 public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1007     protected void realRun() throws InterruptedException {
1008 dl 1.76 delay(SHORT_DELAY_MS);
1009 dl 1.1 }
1010     }
1011    
1012 jsr166 1.45 public class SmallRunnable extends CheckedRunnable {
1013     protected void realRun() throws Throwable {
1014 dl 1.76 delay(SMALL_DELAY_MS);
1015 dl 1.1 }
1016     }
1017    
1018 jsr166 1.45 public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1019     protected void realRun() {
1020 dl 1.6 try {
1021 dl 1.76 delay(SMALL_DELAY_MS);
1022 jsr166 1.44 } catch (InterruptedException ok) {}
1023 dl 1.6 }
1024     }
1025    
1026 jsr166 1.45 public class SmallCallable extends CheckedCallable {
1027     protected Object realCall() throws InterruptedException {
1028 dl 1.76 delay(SMALL_DELAY_MS);
1029 dl 1.1 return Boolean.TRUE;
1030     }
1031     }
1032    
1033 jsr166 1.45 public class MediumRunnable extends CheckedRunnable {
1034     protected void realRun() throws Throwable {
1035 dl 1.76 delay(MEDIUM_DELAY_MS);
1036 dl 1.1 }
1037     }
1038    
1039 jsr166 1.45 public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1040     protected void realRun() throws InterruptedException {
1041 dl 1.76 delay(MEDIUM_DELAY_MS);
1042 dl 1.1 }
1043     }
1044    
1045 jsr166 1.63 public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1046     return new CheckedRunnable() {
1047     protected void realRun() {
1048     try {
1049 dl 1.76 delay(timeoutMillis);
1050 jsr166 1.63 } catch (InterruptedException ok) {}
1051     }};
1052     }
1053    
1054 jsr166 1.45 public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1055     protected void realRun() {
1056 dl 1.1 try {
1057 dl 1.76 delay(MEDIUM_DELAY_MS);
1058 jsr166 1.44 } catch (InterruptedException ok) {}
1059 dl 1.1 }
1060     }
1061 dl 1.5
1062 jsr166 1.45 public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1063     protected void realRun() {
1064 dl 1.12 try {
1065 dl 1.76 delay(LONG_DELAY_MS);
1066 jsr166 1.44 } catch (InterruptedException ok) {}
1067 dl 1.12 }
1068     }
1069    
1070 dl 1.5 /**
1071     * For use as ThreadFactory in constructors
1072     */
1073 jsr166 1.45 public static class SimpleThreadFactory implements ThreadFactory {
1074 jsr166 1.33 public Thread newThread(Runnable r) {
1075 dl 1.5 return new Thread(r);
1076 jsr166 1.27 }
1077 dl 1.5 }
1078    
1079 jsr166 1.61 public interface TrackedRunnable extends Runnable {
1080     boolean isDone();
1081     }
1082    
1083     public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
1084     return new TrackedRunnable() {
1085     private volatile boolean done = false;
1086     public boolean isDone() { return done; }
1087     public void run() {
1088     try {
1089 dl 1.76 delay(timeoutMillis);
1090 jsr166 1.61 done = true;
1091     } catch (InterruptedException ok) {}
1092     }
1093     };
1094     }
1095    
1096 jsr166 1.45 public static class TrackedShortRunnable implements Runnable {
1097     public volatile boolean done = false;
1098 dl 1.5 public void run() {
1099     try {
1100 dl 1.76 delay(SHORT_DELAY_MS);
1101 jsr166 1.61 done = true;
1102     } catch (InterruptedException ok) {}
1103     }
1104     }
1105    
1106     public static class TrackedSmallRunnable implements Runnable {
1107     public volatile boolean done = false;
1108     public void run() {
1109     try {
1110 dl 1.76 delay(SMALL_DELAY_MS);
1111 dl 1.5 done = true;
1112 jsr166 1.44 } catch (InterruptedException ok) {}
1113 dl 1.6 }
1114     }
1115    
1116 jsr166 1.45 public static class TrackedMediumRunnable implements Runnable {
1117     public volatile boolean done = false;
1118 dl 1.6 public void run() {
1119     try {
1120 dl 1.76 delay(MEDIUM_DELAY_MS);
1121 dl 1.6 done = true;
1122 jsr166 1.44 } catch (InterruptedException ok) {}
1123 dl 1.6 }
1124     }
1125    
1126 jsr166 1.45 public static class TrackedLongRunnable implements Runnable {
1127     public volatile boolean done = false;
1128 dl 1.6 public void run() {
1129     try {
1130 dl 1.76 delay(LONG_DELAY_MS);
1131 dl 1.6 done = true;
1132 jsr166 1.44 } catch (InterruptedException ok) {}
1133 dl 1.6 }
1134     }
1135    
1136 jsr166 1.45 public static class TrackedNoOpRunnable implements Runnable {
1137     public volatile boolean done = false;
1138 dl 1.6 public void run() {
1139     done = true;
1140 dl 1.5 }
1141     }
1142    
1143 jsr166 1.45 public static class TrackedCallable implements Callable {
1144     public volatile boolean done = false;
1145 dl 1.5 public Object call() {
1146     try {
1147 dl 1.76 delay(SMALL_DELAY_MS);
1148 dl 1.5 done = true;
1149 jsr166 1.44 } catch (InterruptedException ok) {}
1150 dl 1.5 return Boolean.TRUE;
1151     }
1152     }
1153 dl 1.14
1154 jsr166 1.53 /**
1155     * Analog of CheckedRunnable for RecursiveAction
1156     */
1157     public abstract class CheckedRecursiveAction extends RecursiveAction {
1158     protected abstract void realCompute() throws Throwable;
1159    
1160     public final void compute() {
1161     try {
1162     realCompute();
1163     } catch (Throwable t) {
1164     threadUnexpectedException(t);
1165     }
1166     }
1167     }
1168    
1169     /**
1170     * Analog of CheckedCallable for RecursiveTask
1171     */
1172     public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1173     protected abstract T realCompute() throws Throwable;
1174    
1175     public final T compute() {
1176     try {
1177     return realCompute();
1178     } catch (Throwable t) {
1179     threadUnexpectedException(t);
1180     return null;
1181     }
1182     }
1183     }
1184 dl 1.5
1185     /**
1186     * For use as RejectedExecutionHandler in constructors
1187     */
1188 jsr166 1.45 public static class NoOpREHandler implements RejectedExecutionHandler {
1189 jsr166 1.35 public void rejectedExecution(Runnable r,
1190     ThreadPoolExecutor executor) {}
1191 dl 1.5 }
1192 jsr166 1.27
1193 jsr166 1.60 /**
1194 jsr166 1.86 * A CyclicBarrier that uses timed await and fails with
1195     * AssertionFailedErrors instead of throwing checked exceptions.
1196 jsr166 1.60 */
1197     public class CheckedBarrier extends CyclicBarrier {
1198     public CheckedBarrier(int parties) { super(parties); }
1199    
1200     public int await() {
1201     try {
1202 jsr166 1.86 return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1203     } catch (TimeoutException e) {
1204     throw new AssertionFailedError("timed out");
1205 jsr166 1.60 } catch (Exception e) {
1206     AssertionFailedError afe =
1207     new AssertionFailedError("Unexpected exception: " + e);
1208     afe.initCause(e);
1209     throw afe;
1210     }
1211     }
1212     }
1213    
1214 jsr166 1.81 void checkEmpty(BlockingQueue q) {
1215 jsr166 1.72 try {
1216     assertTrue(q.isEmpty());
1217     assertEquals(0, q.size());
1218     assertNull(q.peek());
1219     assertNull(q.poll());
1220     assertNull(q.poll(0, MILLISECONDS));
1221     assertEquals(q.toString(), "[]");
1222     assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1223     assertFalse(q.iterator().hasNext());
1224     try {
1225     q.element();
1226     shouldThrow();
1227     } catch (NoSuchElementException success) {}
1228     try {
1229     q.iterator().next();
1230     shouldThrow();
1231     } catch (NoSuchElementException success) {}
1232     try {
1233     q.remove();
1234     shouldThrow();
1235     } catch (NoSuchElementException success) {}
1236     } catch (InterruptedException ie) {
1237     threadUnexpectedException(ie);
1238     }
1239     }
1240    
1241 jsr166 1.91 void assertSerialEquals(Object x, Object y) {
1242     assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1243     }
1244    
1245     void assertNotSerialEquals(Object x, Object y) {
1246     assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1247     }
1248    
1249     byte[] serialBytes(Object o) {
1250 jsr166 1.79 try {
1251     ByteArrayOutputStream bos = new ByteArrayOutputStream();
1252     ObjectOutputStream oos = new ObjectOutputStream(bos);
1253     oos.writeObject(o);
1254     oos.flush();
1255     oos.close();
1256 jsr166 1.91 return bos.toByteArray();
1257     } catch (Throwable t) {
1258     threadUnexpectedException(t);
1259     return new byte[0];
1260     }
1261     }
1262    
1263     @SuppressWarnings("unchecked")
1264     <T> T serialClone(T o) {
1265     try {
1266 jsr166 1.87 ObjectInputStream ois = new ObjectInputStream
1267 jsr166 1.91 (new ByteArrayInputStream(serialBytes(o)));
1268 jsr166 1.87 T clone = (T) ois.readObject();
1269     assertSame(o.getClass(), clone.getClass());
1270     return clone;
1271 jsr166 1.79 } catch (Throwable t) {
1272     threadUnexpectedException(t);
1273     return null;
1274     }
1275     }
1276 dl 1.1 }