ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.93
Committed: Sun Dec 16 17:22:42 2012 UTC (11 years, 4 months ago) by jsr166
Branch: MAIN
Changes since 1.92: +25 -1 lines
Log Message:
make testing security manager more flexible and debuggable

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