ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck-jsr166e/JSR166TestCase.java
Revision: 1.1
Committed: Tue Aug 9 07:45:51 2011 UTC (12 years, 10 months ago) by jsr166
Branch: MAIN
Log Message:
tck tests for AtomicDouble

File Contents

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