--- jsr166/src/test/tck/JSR166TestCase.java 2010/11/28 08:43:53 1.72 +++ jsr166/src/test/tck/JSR166TestCase.java 2011/06/03 05:07:14 1.89 @@ -1,16 +1,22 @@ /* * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at - * http://creativecommons.org/licenses/publicdomain + * http://creativecommons.org/publicdomain/zero/1.0/ * Other contributors include Andrew Wright, Jeffrey Hayes, * Pat Fisher, Mike Judd. */ import junit.framework.*; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; import java.util.Arrays; +import java.util.Date; import java.util.NoSuchElementException; import java.util.PropertyPermission; import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.NANOSECONDS; @@ -254,7 +260,6 @@ public class JSR166TestCase extends Test return 50; } - /** * Sets delays as multiples of SHORT_DELAY. */ @@ -266,6 +271,22 @@ public class JSR166TestCase extends Test } /** + * Returns a timeout in milliseconds to be used in tests that + * verify that operations block or time out. + */ + long timeoutMillis() { + return SHORT_DELAY_MS / 4; + } + + /** + * Returns a new Date instance representing a time delayMillis + * milliseconds in the future. + */ + Date delayedDate(long delayMillis) { + return new Date(System.currentTimeMillis() + delayMillis); + } + + /** * The first exception encountered if any threadAssertXXX method fails. */ private final AtomicReference threadFailure @@ -286,9 +307,13 @@ public class JSR166TestCase extends Test } /** + * Extra checks that get done for all test cases. + * * Triggers test case failure if any thread assertions have failed, * by rethrowing, in the test harness thread, any exception recorded * earlier by threadRecordFailure. + * + * Triggers test case failure if interrupt status is set in the main thread. */ public void tearDown() throws Exception { Throwable t = threadFailure.getAndSet(null); @@ -306,6 +331,9 @@ public class JSR166TestCase extends Test throw afe; } } + + if (Thread.interrupted()) + throw new AssertionFailedError("interrupt status set in main thread"); } /** @@ -437,15 +465,36 @@ public class JSR166TestCase extends Test else { AssertionFailedError afe = new AssertionFailedError("unexpected exception: " + t); - t.initCause(t); + afe.initCause(t); throw afe; } } /** + * Delays, via Thread.sleep, for the given millisecond delay, but + * if the sleep is shorter than specified, may re-sleep or yield + * until time elapses. + */ + static void delay(long millis) throws InterruptedException { + long startTime = System.nanoTime(); + long ns = millis * 1000 * 1000; + for (;;) { + if (millis > 0L) + Thread.sleep(millis); + else // too short to sleep + Thread.yield(); + long d = ns - (System.nanoTime() - startTime); + if (d > 0L) + millis = d / (1000 * 1000); + else + break; + } + } + + /** * Waits out termination of a thread pool or fails doing so. */ - public void joinPool(ExecutorService exec) { + void joinPool(ExecutorService exec) { try { exec.shutdown(); assertTrue("ExecutorService did not terminate in a timely manner", @@ -457,6 +506,49 @@ public class JSR166TestCase extends Test } } + /** + * Checks that thread does not terminate within the default + * millisecond delay of {@code timeoutMillis()}. + */ + void assertThreadStaysAlive(Thread thread) { + assertThreadStaysAlive(thread, timeoutMillis()); + } + + /** + * Checks that thread does not terminate within the given millisecond delay. + */ + void assertThreadStaysAlive(Thread thread, long millis) { + try { + // No need to optimize the failing case via Thread.join. + delay(millis); + assertTrue(thread.isAlive()); + } catch (InterruptedException ie) { + fail("Unexpected InterruptedException"); + } + } + + /** + * Checks that future.get times out, with the default timeout of + * {@code timeoutMillis()}. + */ + void assertFutureTimesOut(Future future) { + assertFutureTimesOut(future, timeoutMillis()); + } + + /** + * Checks that future.get times out, with the given millisecond timeout. + */ + void assertFutureTimesOut(Future future, long timeoutMillis) { + long startTime = System.nanoTime(); + try { + future.get(timeoutMillis, MILLISECONDS); + shouldThrow(); + } catch (TimeoutException success) { + } catch (Exception e) { + threadUnexpectedException(e); + } finally { future.cancel(true); } + assertTrue(millisElapsedSince(startTime) >= timeoutMillis); + } /** * Fails with message "should throw exception". @@ -588,7 +680,7 @@ public class JSR166TestCase extends Test */ void sleep(long millis) { try { - Thread.sleep(millis); + delay(millis); } catch (InterruptedException ie) { AssertionFailedError afe = new AssertionFailedError("Unexpected InterruptedException"); @@ -598,22 +690,11 @@ public class JSR166TestCase extends Test } /** - * Sleeps until the timeout has elapsed, or interrupted. - * Does NOT throw InterruptedException. - */ - void sleepTillInterrupted(long timeoutMillis) { - try { - Thread.sleep(timeoutMillis); - } catch (InterruptedException wakeup) {} - } - - /** - * Waits up to the specified number of milliseconds for the given + * Spin-waits up to the specified number of milliseconds for the given * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING. */ void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) { - long timeoutNanos = timeoutMillis * 1000L * 1000L; - long t0 = System.nanoTime(); + long startTime = System.nanoTime(); for (;;) { Thread.State s = thread.getState(); if (s == Thread.State.BLOCKED || @@ -622,7 +703,7 @@ public class JSR166TestCase extends Test return; else if (s == Thread.State.TERMINATED) fail("Unexpected thread termination"); - else if (System.nanoTime() - t0 > timeoutNanos) { + else if (millisElapsedSince(startTime) > timeoutMillis) { threadAssertTrue(thread.isAlive()); return; } @@ -631,6 +712,14 @@ public class JSR166TestCase extends Test } /** + * Waits up to LONG_DELAY_MS for the given thread to enter a wait + * state: BLOCKED, WAITING, or TIMED_WAITING. + */ + void waitForThreadToEnterWaitState(Thread thread) { + waitForThreadToEnterWaitState(thread, LONG_DELAY_MS); + } + + /** * Returns the number of milliseconds since time given by * startNanoTime, which must have been previously returned from a * call to {@link System.nanoTime()}. @@ -660,13 +749,22 @@ public class JSR166TestCase extends Test } catch (InterruptedException ie) { threadUnexpectedException(ie); } finally { - if (t.isAlive()) { + if (t.getState() != Thread.State.TERMINATED) { t.interrupt(); fail("Test timed out"); } } } + /** + * Waits for LONG_DELAY_MS milliseconds for the thread to + * terminate (using {@link Thread#join(long)}), else interrupts + * the thread (in the hope that it may terminate later) and fails. + */ + void awaitTermination(Thread t) { + awaitTermination(t, LONG_DELAY_MS); + } + // Some convenient Runnable classes public abstract class CheckedRunnable implements Runnable { @@ -729,6 +827,7 @@ public class JSR166TestCase extends Test realRun(); threadShouldThrow("InterruptedException"); } catch (InterruptedException success) { + threadAssertFalse(Thread.interrupted()); } catch (Throwable t) { threadUnexpectedException(t); } @@ -758,6 +857,7 @@ public class JSR166TestCase extends Test threadShouldThrow("InterruptedException"); return result; } catch (InterruptedException success) { + threadAssertFalse(Thread.interrupted()); } catch (Throwable t) { threadUnexpectedException(t); } @@ -789,6 +889,48 @@ public class JSR166TestCase extends Test }}; } + public Runnable awaiter(final CountDownLatch latch) { + return new CheckedRunnable() { + public void realRun() throws InterruptedException { + await(latch); + }}; + } + + public void await(CountDownLatch latch) { + try { + assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS)); + } catch (Throwable t) { + threadUnexpectedException(t); + } + } + + public void await(Semaphore semaphore) { + try { + assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS)); + } catch (Throwable t) { + threadUnexpectedException(t); + } + } + +// /** +// * Spin-waits up to LONG_DELAY_MS until flag becomes true. +// */ +// public void await(AtomicBoolean flag) { +// await(flag, LONG_DELAY_MS); +// } + +// /** +// * Spin-waits up to the specified timeout until flag becomes true. +// */ +// public void await(AtomicBoolean flag, long timeoutMillis) { +// long startTime = System.nanoTime(); +// while (!flag.get()) { +// if (millisElapsedSince(startTime) > timeoutMillis) +// throw new AssertionFailedError("timed out"); +// Thread.yield(); +// } +// } + public static class NPETask implements Callable { public String call() { throw new NullPointerException(); } } @@ -799,46 +941,46 @@ public class JSR166TestCase extends Test public class ShortRunnable extends CheckedRunnable { protected void realRun() throws Throwable { - Thread.sleep(SHORT_DELAY_MS); + delay(SHORT_DELAY_MS); } } public class ShortInterruptedRunnable extends CheckedInterruptedRunnable { protected void realRun() throws InterruptedException { - Thread.sleep(SHORT_DELAY_MS); + delay(SHORT_DELAY_MS); } } public class SmallRunnable extends CheckedRunnable { protected void realRun() throws Throwable { - Thread.sleep(SMALL_DELAY_MS); + delay(SMALL_DELAY_MS); } } public class SmallPossiblyInterruptedRunnable extends CheckedRunnable { protected void realRun() { try { - Thread.sleep(SMALL_DELAY_MS); + delay(SMALL_DELAY_MS); } catch (InterruptedException ok) {} } } public class SmallCallable extends CheckedCallable { protected Object realCall() throws InterruptedException { - Thread.sleep(SMALL_DELAY_MS); + delay(SMALL_DELAY_MS); return Boolean.TRUE; } } public class MediumRunnable extends CheckedRunnable { protected void realRun() throws Throwable { - Thread.sleep(MEDIUM_DELAY_MS); + delay(MEDIUM_DELAY_MS); } } public class MediumInterruptedRunnable extends CheckedInterruptedRunnable { protected void realRun() throws InterruptedException { - Thread.sleep(MEDIUM_DELAY_MS); + delay(MEDIUM_DELAY_MS); } } @@ -846,7 +988,7 @@ public class JSR166TestCase extends Test return new CheckedRunnable() { protected void realRun() { try { - Thread.sleep(timeoutMillis); + delay(timeoutMillis); } catch (InterruptedException ok) {} }}; } @@ -854,7 +996,7 @@ public class JSR166TestCase extends Test public class MediumPossiblyInterruptedRunnable extends CheckedRunnable { protected void realRun() { try { - Thread.sleep(MEDIUM_DELAY_MS); + delay(MEDIUM_DELAY_MS); } catch (InterruptedException ok) {} } } @@ -862,7 +1004,7 @@ public class JSR166TestCase extends Test public class LongPossiblyInterruptedRunnable extends CheckedRunnable { protected void realRun() { try { - Thread.sleep(LONG_DELAY_MS); + delay(LONG_DELAY_MS); } catch (InterruptedException ok) {} } } @@ -886,7 +1028,7 @@ public class JSR166TestCase extends Test public boolean isDone() { return done; } public void run() { try { - Thread.sleep(timeoutMillis); + delay(timeoutMillis); done = true; } catch (InterruptedException ok) {} } @@ -897,7 +1039,7 @@ public class JSR166TestCase extends Test public volatile boolean done = false; public void run() { try { - Thread.sleep(SHORT_DELAY_MS); + delay(SHORT_DELAY_MS); done = true; } catch (InterruptedException ok) {} } @@ -907,7 +1049,7 @@ public class JSR166TestCase extends Test public volatile boolean done = false; public void run() { try { - Thread.sleep(SMALL_DELAY_MS); + delay(SMALL_DELAY_MS); done = true; } catch (InterruptedException ok) {} } @@ -917,7 +1059,7 @@ public class JSR166TestCase extends Test public volatile boolean done = false; public void run() { try { - Thread.sleep(MEDIUM_DELAY_MS); + delay(MEDIUM_DELAY_MS); done = true; } catch (InterruptedException ok) {} } @@ -927,7 +1069,7 @@ public class JSR166TestCase extends Test public volatile boolean done = false; public void run() { try { - Thread.sleep(LONG_DELAY_MS); + delay(LONG_DELAY_MS); done = true; } catch (InterruptedException ok) {} } @@ -944,7 +1086,7 @@ public class JSR166TestCase extends Test public volatile boolean done = false; public Object call() { try { - Thread.sleep(SMALL_DELAY_MS); + delay(SMALL_DELAY_MS); done = true; } catch (InterruptedException ok) {} return Boolean.TRUE; @@ -991,15 +1133,17 @@ public class JSR166TestCase extends Test } /** - * A CyclicBarrier that fails with AssertionFailedErrors instead - * of throwing checked exceptions. + * A CyclicBarrier that uses timed await and fails with + * AssertionFailedErrors instead of throwing checked exceptions. */ public class CheckedBarrier extends CyclicBarrier { public CheckedBarrier(int parties) { super(parties); } public int await() { try { - return super.await(); + return super.await(2 * LONG_DELAY_MS, MILLISECONDS); + } catch (TimeoutException e) { + throw new AssertionFailedError("timed out"); } catch (Exception e) { AssertionFailedError afe = new AssertionFailedError("Unexpected exception: " + e); @@ -1009,7 +1153,7 @@ public class JSR166TestCase extends Test } } - public void checkEmpty(BlockingQueue q) { + void checkEmpty(BlockingQueue q) { try { assertTrue(q.isEmpty()); assertEquals(0, q.size()); @@ -1036,4 +1180,22 @@ public class JSR166TestCase extends Test } } + @SuppressWarnings("unchecked") + T serialClone(T o) { + try { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + ObjectOutputStream oos = new ObjectOutputStream(bos); + oos.writeObject(o); + oos.flush(); + oos.close(); + ObjectInputStream ois = new ObjectInputStream + (new ByteArrayInputStream(bos.toByteArray())); + T clone = (T) ois.readObject(); + assertSame(o.getClass(), clone.getClass()); + return clone; + } catch (Throwable t) { + threadUnexpectedException(t); + return null; + } + } }