--- jsr166/src/test/tck/JSR166TestCase.java 2011/05/13 21:48:58 1.80
+++ jsr166/src/test/tck/JSR166TestCase.java 2013/01/21 19:32:19 1.94
@@ -11,10 +11,15 @@ import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
+import java.util.ArrayList;
import java.util.Arrays;
+import java.util.Date;
+import java.util.Enumeration;
+import java.util.List;
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;
@@ -67,7 +72,7 @@ import java.security.SecurityPermission;
*
*
*
- *
Other notes
+ *
Other notes
*
*
* - Usually, there is one testcase method per JSR166 method
@@ -140,7 +145,9 @@ public class JSR166TestCase extends Test
}
/**
- * Runs all JSR166 unit tests using junit.textui.TestRunner
+ * Runs all JSR166 unit tests using junit.textui.TestRunner.
+ * Optional command line arg provides the number of iterations to
+ * repeat running the tests.
*/
public static void main(String[] args) {
if (useSecurityManager) {
@@ -258,7 +265,6 @@ public class JSR166TestCase extends Test
return 50;
}
-
/**
* Sets delays as multiples of SHORT_DELAY.
*/
@@ -270,6 +276,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
@@ -290,9 +312,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);
@@ -310,6 +336,9 @@ public class JSR166TestCase extends Test
throw afe;
}
}
+
+ if (Thread.interrupted())
+ throw new AssertionFailedError("interrupt status set in main thread");
}
/**
@@ -441,17 +470,17 @@ 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
+ * 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.
*/
- public static void delay(long millis) throws InterruptedException {
+ static void delay(long millis) throws InterruptedException {
long startTime = System.nanoTime();
long ns = millis * 1000 * 1000;
for (;;) {
@@ -470,7 +499,7 @@ public class JSR166TestCase extends Test
/**
* 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",
@@ -483,9 +512,17 @@ 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.
*/
- public void assertThreadStaysAlive(Thread thread, long millis) {
+ void assertThreadStaysAlive(Thread thread, long millis) {
try {
// No need to optimize the failing case via Thread.join.
delay(millis);
@@ -496,6 +533,51 @@ public class JSR166TestCase extends Test
}
/**
+ * Checks that the threads do not terminate within the default
+ * millisecond delay of {@code timeoutMillis()}.
+ */
+ void assertThreadsStayAlive(Thread... threads) {
+ assertThreadsStayAlive(timeoutMillis(), threads);
+ }
+
+ /**
+ * Checks that the threads do not terminate within the given millisecond delay.
+ */
+ void assertThreadsStayAlive(long millis, Thread... threads) {
+ try {
+ // No need to optimize the failing case via Thread.join.
+ delay(millis);
+ for (Thread thread : threads)
+ 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".
*/
public void shouldThrow() {
@@ -546,11 +628,26 @@ public class JSR166TestCase extends Test
SecurityManager sm = System.getSecurityManager();
if (sm == null) {
r.run();
+ }
+ runWithSecurityManagerWithPermissions(r, permissions);
+ }
+
+ /**
+ * Runs Runnable r with a security policy that permits precisely
+ * the specified permissions. If there is no current security
+ * manager, a temporary one is set for the duration of the
+ * Runnable. We require that any security manager permit
+ * getPolicy/setPolicy.
+ */
+ public void runWithSecurityManagerWithPermissions(Runnable r,
+ Permission... permissions) {
+ SecurityManager sm = System.getSecurityManager();
+ if (sm == null) {
Policy savedPolicy = Policy.getPolicy();
try {
Policy.setPolicy(permissivePolicy());
System.setSecurityManager(new SecurityManager());
- runWithPermissions(r, permissions);
+ runWithSecurityManagerWithPermissions(r, permissions);
} finally {
System.setSecurityManager(null);
Policy.setPolicy(savedPolicy);
@@ -598,6 +695,12 @@ public class JSR166TestCase extends Test
return perms.implies(p);
}
public void refresh() {}
+ public String toString() {
+ List ps = new ArrayList();
+ for (Enumeration e = perms.elements(); e.hasMoreElements();)
+ ps.add(e.nextElement());
+ return "AdjustablePolicy with permissions " + ps;
+ }
}
/**
@@ -635,22 +738,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 ||
@@ -659,7 +751,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;
}
@@ -705,7 +797,7 @@ 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");
}
@@ -783,6 +875,7 @@ public class JSR166TestCase extends Test
realRun();
threadShouldThrow("InterruptedException");
} catch (InterruptedException success) {
+ threadAssertFalse(Thread.interrupted());
} catch (Throwable t) {
threadUnexpectedException(t);
}
@@ -812,6 +905,7 @@ public class JSR166TestCase extends Test
threadShouldThrow("InterruptedException");
return result;
} catch (InterruptedException success) {
+ threadAssertFalse(Thread.interrupted());
} catch (Throwable t) {
threadUnexpectedException(t);
}
@@ -858,6 +952,33 @@ public class JSR166TestCase extends Test
}
}
+ 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(); }
}
@@ -1060,15 +1181,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);
@@ -1078,7 +1201,7 @@ public class JSR166TestCase extends Test
}
}
- public void checkEmpty(BlockingQueue q) {
+ void checkEmpty(BlockingQueue q) {
try {
assertTrue(q.isEmpty());
assertEquals(0, q.size());
@@ -1105,18 +1228,36 @@ public class JSR166TestCase extends Test
}
}
- @SuppressWarnings("unchecked")
- public T serialClone(T o) {
+ void assertSerialEquals(Object x, Object y) {
+ assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
+ }
+
+ void assertNotSerialEquals(Object x, Object y) {
+ assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
+ }
+
+ byte[] serialBytes(Object o) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(o);
oos.flush();
oos.close();
- ByteArrayInputStream bin =
- new ByteArrayInputStream(bos.toByteArray());
- ObjectInputStream ois = new ObjectInputStream(bin);
- return (T) ois.readObject();
+ return bos.toByteArray();
+ } catch (Throwable t) {
+ threadUnexpectedException(t);
+ return new byte[0];
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ T serialClone(T o) {
+ try {
+ ObjectInputStream ois = new ObjectInputStream
+ (new ByteArrayInputStream(serialBytes(o)));
+ T clone = (T) ois.readObject();
+ assertSame(o.getClass(), clone.getClass());
+ return clone;
} catch (Throwable t) {
threadUnexpectedException(t);
return null;