8195590: Miscellaneous changes imported from jsr166 CVS 2018-02

Reviewed-by: martin, psandoz, dholmes
This commit is contained in:
Doug Lea 2018-02-10 09:23:41 -08:00
parent b6c2b234ef
commit f9b19eb874
16 changed files with 187 additions and 186 deletions

View file

@ -1584,7 +1584,17 @@ public class ArrayBlockingQueue<E> extends AbstractQueue<E>
void checkInvariants() { void checkInvariants() {
// meta-assertions // meta-assertions
// assert lock.isHeldByCurrentThread(); // assert lock.isHeldByCurrentThread();
try { if (!invariantsSatisfied()) {
String detail = String.format(
"takeIndex=%d putIndex=%d count=%d capacity=%d items=%s",
takeIndex, putIndex, count, items.length,
Arrays.toString(items));
System.err.println(detail);
throw new AssertionError(detail);
}
}
private boolean invariantsSatisfied() {
// Unlike ArrayDeque, we have a count field but no spare slot. // Unlike ArrayDeque, we have a count field but no spare slot.
// We prefer ArrayDeque's strategy (and the names of its fields!), // We prefer ArrayDeque's strategy (and the names of its fields!),
// but our field layout is baked into the serial form, and so is // but our field layout is baked into the serial form, and so is
@ -1592,26 +1602,22 @@ public class ArrayBlockingQueue<E> extends AbstractQueue<E>
// //
// putIndex == takeIndex must be disambiguated by checking count. // putIndex == takeIndex must be disambiguated by checking count.
int capacity = items.length; int capacity = items.length;
// assert capacity > 0; return capacity > 0
// assert takeIndex >= 0 && takeIndex < capacity; && items.getClass() == Object[].class
// assert putIndex >= 0 && putIndex < capacity; && (takeIndex | putIndex | count) >= 0
// assert count <= capacity; && takeIndex < capacity
// assert takeIndex == putIndex || items[takeIndex] != null; && putIndex < capacity
// assert count == capacity || items[putIndex] == null; && count <= capacity
// assert takeIndex == putIndex || items[dec(putIndex, capacity)] != null; && (putIndex - takeIndex - count) % capacity == 0
} catch (Throwable t) { && (count == 0 || items[takeIndex] != null)
System.err.printf("takeIndex=%d putIndex=%d count=%d capacity=%d%n", && (count == capacity || items[putIndex] == null)
takeIndex, putIndex, count, items.length); && (count == 0 || items[dec(putIndex, capacity)] != null);
System.err.printf("items=%s%n",
Arrays.toString(items));
throw t;
}
} }
/** /**
* Deserializes this queue and then checks some invariants. * Reconstitutes this queue from a stream (that is, deserializes it).
* *
* @param s the input stream * @param s the stream
* @throws ClassNotFoundException if the class of a serialized object * @throws ClassNotFoundException if the class of a serialized object
* could not be found * could not be found
* @throws java.io.InvalidObjectException if invariants are violated * @throws java.io.InvalidObjectException if invariants are violated
@ -1623,15 +1629,7 @@ public class ArrayBlockingQueue<E> extends AbstractQueue<E>
// Read in items array and various fields // Read in items array and various fields
s.defaultReadObject(); s.defaultReadObject();
// Check invariants over count and index fields. Note that if (!invariantsSatisfied())
// if putIndex==takeIndex, count can be either 0 or items.length.
if (items.length == 0 ||
takeIndex < 0 || takeIndex >= items.length ||
putIndex < 0 || putIndex >= items.length ||
count < 0 || count > items.length ||
Math.floorMod(putIndex - takeIndex, items.length) !=
Math.floorMod(count, items.length)) {
throw new java.io.InvalidObjectException("invariants violated"); throw new java.io.InvalidObjectException("invariants violated");
} }
} }
}

View file

@ -35,6 +35,7 @@
package java.util.concurrent; package java.util.concurrent;
import static java.lang.ref.Reference.reachabilityFence;
import java.security.AccessControlContext; import java.security.AccessControlContext;
import java.security.AccessControlException; import java.security.AccessControlException;
import java.security.AccessController; import java.security.AccessController;
@ -185,9 +186,7 @@ public class Executors {
* returned executor is guaranteed not to be reconfigurable to use * returned executor is guaranteed not to be reconfigurable to use
* additional threads. * additional threads.
* *
* @param threadFactory the factory to use when creating new * @param threadFactory the factory to use when creating new threads
* threads
*
* @return the newly created single-threaded Executor * @return the newly created single-threaded Executor
* @throws NullPointerException if threadFactory is null * @throws NullPointerException if threadFactory is null
*/ */
@ -226,6 +225,7 @@ public class Executors {
* will reuse previously constructed threads when they are * will reuse previously constructed threads when they are
* available, and uses the provided * available, and uses the provided
* ThreadFactory to create new threads when needed. * ThreadFactory to create new threads when needed.
*
* @param threadFactory the factory to use when creating new threads * @param threadFactory the factory to use when creating new threads
* @return the newly created thread pool * @return the newly created thread pool
* @throws NullPointerException if threadFactory is null * @throws NullPointerException if threadFactory is null
@ -248,6 +248,7 @@ public class Executors {
* given time. Unlike the otherwise equivalent * given time. Unlike the otherwise equivalent
* {@code newScheduledThreadPool(1)} the returned executor is * {@code newScheduledThreadPool(1)} the returned executor is
* guaranteed not to be reconfigurable to use additional threads. * guaranteed not to be reconfigurable to use additional threads.
*
* @return the newly created scheduled executor * @return the newly created scheduled executor
*/ */
public static ScheduledExecutorService newSingleThreadScheduledExecutor() { public static ScheduledExecutorService newSingleThreadScheduledExecutor() {
@ -266,9 +267,9 @@ public class Executors {
* equivalent {@code newScheduledThreadPool(1, threadFactory)} * equivalent {@code newScheduledThreadPool(1, threadFactory)}
* the returned executor is guaranteed not to be reconfigurable to * the returned executor is guaranteed not to be reconfigurable to
* use additional threads. * use additional threads.
* @param threadFactory the factory to use when creating new *
* threads * @param threadFactory the factory to use when creating new threads
* @return a newly created scheduled executor * @return the newly created scheduled executor
* @throws NullPointerException if threadFactory is null * @throws NullPointerException if threadFactory is null
*/ */
public static ScheduledExecutorService newSingleThreadScheduledExecutor(ThreadFactory threadFactory) { public static ScheduledExecutorService newSingleThreadScheduledExecutor(ThreadFactory threadFactory) {
@ -281,7 +282,7 @@ public class Executors {
* given delay, or to execute periodically. * given delay, or to execute periodically.
* @param corePoolSize the number of threads to keep in the pool, * @param corePoolSize the number of threads to keep in the pool,
* even if they are idle * even if they are idle
* @return a newly created scheduled thread pool * @return the newly created scheduled thread pool
* @throws IllegalArgumentException if {@code corePoolSize < 0} * @throws IllegalArgumentException if {@code corePoolSize < 0}
*/ */
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) { public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
@ -295,7 +296,7 @@ public class Executors {
* even if they are idle * even if they are idle
* @param threadFactory the factory to use when the executor * @param threadFactory the factory to use when the executor
* creates a new thread * creates a new thread
* @return a newly created scheduled thread pool * @return the newly created scheduled thread pool
* @throws IllegalArgumentException if {@code corePoolSize < 0} * @throws IllegalArgumentException if {@code corePoolSize < 0}
* @throws NullPointerException if threadFactory is null * @throws NullPointerException if threadFactory is null
*/ */
@ -678,44 +679,76 @@ public class Executors {
* of an ExecutorService implementation. * of an ExecutorService implementation.
*/ */
private static class DelegatedExecutorService private static class DelegatedExecutorService
extends AbstractExecutorService { implements ExecutorService {
private final ExecutorService e; private final ExecutorService e;
DelegatedExecutorService(ExecutorService executor) { e = executor; } DelegatedExecutorService(ExecutorService executor) { e = executor; }
public void execute(Runnable command) { e.execute(command); } public void execute(Runnable command) {
try {
e.execute(command);
} finally { reachabilityFence(this); }
}
public void shutdown() { e.shutdown(); } public void shutdown() { e.shutdown(); }
public List<Runnable> shutdownNow() { return e.shutdownNow(); } public List<Runnable> shutdownNow() {
public boolean isShutdown() { return e.isShutdown(); } try {
public boolean isTerminated() { return e.isTerminated(); } return e.shutdownNow();
} finally { reachabilityFence(this); }
}
public boolean isShutdown() {
try {
return e.isShutdown();
} finally { reachabilityFence(this); }
}
public boolean isTerminated() {
try {
return e.isTerminated();
} finally { reachabilityFence(this); }
}
public boolean awaitTermination(long timeout, TimeUnit unit) public boolean awaitTermination(long timeout, TimeUnit unit)
throws InterruptedException { throws InterruptedException {
try {
return e.awaitTermination(timeout, unit); return e.awaitTermination(timeout, unit);
} finally { reachabilityFence(this); }
} }
public Future<?> submit(Runnable task) { public Future<?> submit(Runnable task) {
try {
return e.submit(task); return e.submit(task);
} finally { reachabilityFence(this); }
} }
public <T> Future<T> submit(Callable<T> task) { public <T> Future<T> submit(Callable<T> task) {
try {
return e.submit(task); return e.submit(task);
} finally { reachabilityFence(this); }
} }
public <T> Future<T> submit(Runnable task, T result) { public <T> Future<T> submit(Runnable task, T result) {
try {
return e.submit(task, result); return e.submit(task, result);
} finally { reachabilityFence(this); }
} }
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
throws InterruptedException { throws InterruptedException {
try {
return e.invokeAll(tasks); return e.invokeAll(tasks);
} finally { reachabilityFence(this); }
} }
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
long timeout, TimeUnit unit) long timeout, TimeUnit unit)
throws InterruptedException { throws InterruptedException {
try {
return e.invokeAll(tasks, timeout, unit); return e.invokeAll(tasks, timeout, unit);
} finally { reachabilityFence(this); }
} }
public <T> T invokeAny(Collection<? extends Callable<T>> tasks) public <T> T invokeAny(Collection<? extends Callable<T>> tasks)
throws InterruptedException, ExecutionException { throws InterruptedException, ExecutionException {
try {
return e.invokeAny(tasks); return e.invokeAny(tasks);
} finally { reachabilityFence(this); }
} }
public <T> T invokeAny(Collection<? extends Callable<T>> tasks, public <T> T invokeAny(Collection<? extends Callable<T>> tasks,
long timeout, TimeUnit unit) long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException { throws InterruptedException, ExecutionException, TimeoutException {
try {
return e.invokeAny(tasks, timeout, unit); return e.invokeAny(tasks, timeout, unit);
} finally { reachabilityFence(this); }
} }
} }

View file

@ -323,10 +323,8 @@ public class LinkedBlockingQueue<E> extends AbstractQueue<E>
*/ */
public void put(E e) throws InterruptedException { public void put(E e) throws InterruptedException {
if (e == null) throw new NullPointerException(); if (e == null) throw new NullPointerException();
// Note: convention in all put/take/etc is to preset local var final int c;
// holding count negative to indicate failure unless set. final Node<E> node = new Node<E>(e);
int c = -1;
Node<E> node = new Node<E>(e);
final ReentrantLock putLock = this.putLock; final ReentrantLock putLock = this.putLock;
final AtomicInteger count = this.count; final AtomicInteger count = this.count;
putLock.lockInterruptibly(); putLock.lockInterruptibly();
@ -367,7 +365,7 @@ public class LinkedBlockingQueue<E> extends AbstractQueue<E>
if (e == null) throw new NullPointerException(); if (e == null) throw new NullPointerException();
long nanos = unit.toNanos(timeout); long nanos = unit.toNanos(timeout);
int c = -1; final int c;
final ReentrantLock putLock = this.putLock; final ReentrantLock putLock = this.putLock;
final AtomicInteger count = this.count; final AtomicInteger count = this.count;
putLock.lockInterruptibly(); putLock.lockInterruptibly();
@ -405,28 +403,28 @@ public class LinkedBlockingQueue<E> extends AbstractQueue<E>
final AtomicInteger count = this.count; final AtomicInteger count = this.count;
if (count.get() == capacity) if (count.get() == capacity)
return false; return false;
int c = -1; final int c;
Node<E> node = new Node<E>(e); final Node<E> node = new Node<E>(e);
final ReentrantLock putLock = this.putLock; final ReentrantLock putLock = this.putLock;
putLock.lock(); putLock.lock();
try { try {
if (count.get() < capacity) { if (count.get() == capacity)
return false;
enqueue(node); enqueue(node);
c = count.getAndIncrement(); c = count.getAndIncrement();
if (c + 1 < capacity) if (c + 1 < capacity)
notFull.signal(); notFull.signal();
}
} finally { } finally {
putLock.unlock(); putLock.unlock();
} }
if (c == 0) if (c == 0)
signalNotEmpty(); signalNotEmpty();
return c >= 0; return true;
} }
public E take() throws InterruptedException { public E take() throws InterruptedException {
E x; final E x;
int c = -1; final int c;
final AtomicInteger count = this.count; final AtomicInteger count = this.count;
final ReentrantLock takeLock = this.takeLock; final ReentrantLock takeLock = this.takeLock;
takeLock.lockInterruptibly(); takeLock.lockInterruptibly();
@ -447,8 +445,8 @@ public class LinkedBlockingQueue<E> extends AbstractQueue<E>
} }
public E poll(long timeout, TimeUnit unit) throws InterruptedException { public E poll(long timeout, TimeUnit unit) throws InterruptedException {
E x = null; final E x;
int c = -1; final int c;
long nanos = unit.toNanos(timeout); long nanos = unit.toNanos(timeout);
final AtomicInteger count = this.count; final AtomicInteger count = this.count;
final ReentrantLock takeLock = this.takeLock; final ReentrantLock takeLock = this.takeLock;
@ -475,17 +473,17 @@ public class LinkedBlockingQueue<E> extends AbstractQueue<E>
final AtomicInteger count = this.count; final AtomicInteger count = this.count;
if (count.get() == 0) if (count.get() == 0)
return null; return null;
E x = null; final E x;
int c = -1; final int c;
final ReentrantLock takeLock = this.takeLock; final ReentrantLock takeLock = this.takeLock;
takeLock.lock(); takeLock.lock();
try { try {
if (count.get() > 0) { if (count.get() == 0)
return null;
x = dequeue(); x = dequeue();
c = count.getAndDecrement(); c = count.getAndDecrement();
if (c > 1) if (c > 1)
notEmpty.signal(); notEmpty.signal();
}
} finally { } finally {
takeLock.unlock(); takeLock.unlock();
} }
@ -495,6 +493,7 @@ public class LinkedBlockingQueue<E> extends AbstractQueue<E>
} }
public E peek() { public E peek() {
final AtomicInteger count = this.count;
if (count.get() == 0) if (count.get() == 0)
return null; return null;
final ReentrantLock takeLock = this.takeLock; final ReentrantLock takeLock = this.takeLock;

View file

@ -48,10 +48,11 @@ public class AbstractMapClone extends AbstractMap implements Cloneable {
} }
public Object clone() { public Object clone() {
AbstractMapClone clone = null; final AbstractMapClone clone;
try { try {
clone = (AbstractMapClone)super.clone(); clone = (AbstractMapClone)super.clone();
} catch (CloneNotSupportedException e) { } catch (CloneNotSupportedException e) {
throw new AssertionError(e);
} }
clone.map = (Map)((HashMap)map).clone(); clone.map = (Map)((HashMap)map).clone();
return clone; return clone;

View file

@ -163,10 +163,7 @@ public class EmptyNavigableSet {
*/ */
@Test(dataProvider = "NavigableSet<?>", dataProviderClass = EmptyNavigableSet.class) @Test(dataProvider = "NavigableSet<?>", dataProviderClass = EmptyNavigableSet.class)
public void testEmptyIterator(String description, NavigableSet<?> navigableSet) { public void testEmptyIterator(String description, NavigableSet<?> navigableSet) {
Iterator emptyIterator = navigableSet.iterator(); assertFalse(navigableSet.iterator().hasNext(), "The iterator is not empty.");
assertFalse((emptyIterator != null) && (emptyIterator.hasNext()),
"The iterator is not empty.");
} }
/** /**

View file

@ -181,7 +181,7 @@ public class WhiteBox {
Object x = it.next(); Object x = it.next();
assertSame(x, a[i]); assertSame(x, a[i]);
assertSame(x, b[i]); assertSame(x, b[i]);
if (xx != null) assertSame(x, yy[i]); assertSame(x, yy[i]);
} }
if (rnd.nextBoolean()) assertTrue(!it.hasNext()); if (rnd.nextBoolean()) assertTrue(!it.hasNext());
} }

View file

@ -43,7 +43,6 @@ import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.locks.AbstractQueuedLongSynchronizer; import java.util.concurrent.locks.AbstractQueuedLongSynchronizer;
import java.util.concurrent.locks.AbstractQueuedLongSynchronizer.ConditionObject; import java.util.concurrent.locks.AbstractQueuedLongSynchronizer.ConditionObject;
import junit.framework.AssertionFailedError;
import junit.framework.Test; import junit.framework.Test;
import junit.framework.TestSuite; import junit.framework.TestSuite;
@ -168,7 +167,7 @@ public class AbstractQueuedLongSynchronizerTest extends JSR166TestCase {
long startTime = System.nanoTime(); long startTime = System.nanoTime();
while (!sync.isQueued(t)) { while (!sync.isQueued(t)) {
if (millisElapsedSince(startTime) > LONG_DELAY_MS) if (millisElapsedSince(startTime) > LONG_DELAY_MS)
throw new AssertionFailedError("timed out"); throw new AssertionError("timed out");
Thread.yield(); Thread.yield();
} }
assertTrue(t.isAlive()); assertTrue(t.isAlive());

View file

@ -44,7 +44,6 @@ import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.locks.AbstractQueuedSynchronizer; import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.AbstractQueuedSynchronizer.ConditionObject; import java.util.concurrent.locks.AbstractQueuedSynchronizer.ConditionObject;
import junit.framework.AssertionFailedError;
import junit.framework.Test; import junit.framework.Test;
import junit.framework.TestSuite; import junit.framework.TestSuite;
@ -172,7 +171,7 @@ public class AbstractQueuedSynchronizerTest extends JSR166TestCase {
long startTime = System.nanoTime(); long startTime = System.nanoTime();
while (!sync.isQueued(t)) { while (!sync.isQueued(t)) {
if (millisElapsedSince(startTime) > LONG_DELAY_MS) if (millisElapsedSince(startTime) > LONG_DELAY_MS)
throw new AssertionFailedError("timed out"); throw new AssertionError("timed out");
Thread.yield(); Thread.yield();
} }
assertTrue(t.isAlive()); assertTrue(t.isAlive());

View file

@ -68,7 +68,6 @@ import java.util.function.Function;
import java.util.function.Predicate; import java.util.function.Predicate;
import java.util.function.Supplier; import java.util.function.Supplier;
import junit.framework.AssertionFailedError;
import junit.framework.Test; import junit.framework.Test;
import junit.framework.TestSuite; import junit.framework.TestSuite;
@ -319,7 +318,7 @@ public class CompletableFutureTest extends JSR166TestCase {
} }
f = new CompletableFuture<>(); f = new CompletableFuture<>();
f.completeExceptionally(ex = new CFException()); f.completeExceptionally(new CFException());
f.obtrudeValue(v1); f.obtrudeValue(v1);
checkCompletedNormally(f, v1); checkCompletedNormally(f, v1);
f.obtrudeException(ex = new CFException()); f.obtrudeException(ex = new CFException());
@ -4217,7 +4216,7 @@ public class CompletableFutureTest extends JSR166TestCase {
static void assertZero(CompletableFuture<?> f) { static void assertZero(CompletableFuture<?> f) {
try { try {
f.getNow(null); f.getNow(null);
throw new AssertionFailedError("should throw"); throw new AssertionError("should throw");
} catch (CompletionException success) { } catch (CompletionException success) {
assertTrue(success.getCause() instanceof ZeroException); assertTrue(success.getCause() instanceof ZeroException);
} }

View file

@ -55,7 +55,6 @@ import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantLock;
import junit.framework.AssertionFailedError;
import junit.framework.Test; import junit.framework.Test;
import junit.framework.TestSuite; import junit.framework.TestSuite;
@ -331,7 +330,7 @@ public class ForkJoinPoolTest extends JSR166TestCase {
p.getFactory()); p.getFactory());
while (! p.isQuiescent()) { while (! p.isQuiescent()) {
if (millisElapsedSince(startTime) > LONG_DELAY_MS) if (millisElapsedSince(startTime) > LONG_DELAY_MS)
throw new AssertionFailedError("timed out"); throw new AssertionError("timed out");
assertFalse(p.getAsyncMode()); assertFalse(p.getAsyncMode());
assertFalse(p.isShutdown()); assertFalse(p.isShutdown());
assertFalse(p.isTerminating()); assertFalse(p.isTerminating());

View file

@ -126,7 +126,6 @@ import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import junit.framework.AssertionFailedError;
import junit.framework.Test; import junit.framework.Test;
import junit.framework.TestCase; import junit.framework.TestCase;
import junit.framework.TestResult; import junit.framework.TestResult;
@ -446,11 +445,10 @@ public class JSR166TestCase extends TestCase {
for (String testClassName : testClassNames) { for (String testClassName : testClassNames) {
try { try {
Class<?> testClass = Class.forName(testClassName); Class<?> testClass = Class.forName(testClassName);
Method m = testClass.getDeclaredMethod("suite", Method m = testClass.getDeclaredMethod("suite");
new Class<?>[0]);
suite.addTest(newTestSuite((Test)m.invoke(null))); suite.addTest(newTestSuite((Test)m.invoke(null)));
} catch (Exception e) { } catch (ReflectiveOperationException e) {
throw new Error("Missing test class", e); throw new AssertionError("Missing test class", e);
} }
} }
} }
@ -627,8 +625,8 @@ public class JSR166TestCase extends TestCase {
for (String methodName : testMethodNames(testClass)) for (String methodName : testMethodNames(testClass))
suite.addTest((Test) c.newInstance(data, methodName)); suite.addTest((Test) c.newInstance(data, methodName));
return suite; return suite;
} catch (Exception e) { } catch (ReflectiveOperationException e) {
throw new Error(e); throw new AssertionError(e);
} }
} }
@ -644,14 +642,14 @@ public class JSR166TestCase extends TestCase {
if (atLeastJava8()) { if (atLeastJava8()) {
String name = testClass.getName(); String name = testClass.getName();
String name8 = name.replaceAll("Test$", "8Test"); String name8 = name.replaceAll("Test$", "8Test");
if (name.equals(name8)) throw new Error(name); if (name.equals(name8)) throw new AssertionError(name);
try { try {
return (Test) return (Test)
Class.forName(name8) Class.forName(name8)
.getMethod("testSuite", new Class[] { dataClass }) .getMethod("testSuite", dataClass)
.invoke(null, data); .invoke(null, data);
} catch (Exception e) { } catch (ReflectiveOperationException e) {
throw new Error(e); throw new AssertionError(e);
} }
} else { } else {
return new TestSuite(); return new TestSuite();
@ -760,7 +758,7 @@ public class JSR166TestCase extends TestCase {
String msg = toString() + ": " + String.format(format, args); String msg = toString() + ": " + String.format(format, args);
System.err.println(msg); System.err.println(msg);
dumpTestThreads(); dumpTestThreads();
throw new AssertionFailedError(msg); throw new AssertionError(msg);
} }
/** /**
@ -781,12 +779,8 @@ public class JSR166TestCase extends TestCase {
throw (RuntimeException) t; throw (RuntimeException) t;
else if (t instanceof Exception) else if (t instanceof Exception)
throw (Exception) t; throw (Exception) t;
else { else
AssertionFailedError afe = throw new AssertionError(t.toString(), t);
new AssertionFailedError(t.toString());
afe.initCause(t);
throw afe;
}
} }
if (Thread.interrupted()) if (Thread.interrupted())
@ -820,83 +814,83 @@ public class JSR166TestCase extends TestCase {
/** /**
* Just like fail(reason), but additionally recording (using * Just like fail(reason), but additionally recording (using
* threadRecordFailure) any AssertionFailedError thrown, so that * threadRecordFailure) any AssertionError thrown, so that the
* the current testcase will fail. * current testcase will fail.
*/ */
public void threadFail(String reason) { public void threadFail(String reason) {
try { try {
fail(reason); fail(reason);
} catch (AssertionFailedError t) { } catch (AssertionError fail) {
threadRecordFailure(t); threadRecordFailure(fail);
throw t; throw fail;
} }
} }
/** /**
* Just like assertTrue(b), but additionally recording (using * Just like assertTrue(b), but additionally recording (using
* threadRecordFailure) any AssertionFailedError thrown, so that * threadRecordFailure) any AssertionError thrown, so that the
* the current testcase will fail. * current testcase will fail.
*/ */
public void threadAssertTrue(boolean b) { public void threadAssertTrue(boolean b) {
try { try {
assertTrue(b); assertTrue(b);
} catch (AssertionFailedError t) { } catch (AssertionError fail) {
threadRecordFailure(t); threadRecordFailure(fail);
throw t; throw fail;
} }
} }
/** /**
* Just like assertFalse(b), but additionally recording (using * Just like assertFalse(b), but additionally recording (using
* threadRecordFailure) any AssertionFailedError thrown, so that * threadRecordFailure) any AssertionError thrown, so that the
* the current testcase will fail. * current testcase will fail.
*/ */
public void threadAssertFalse(boolean b) { public void threadAssertFalse(boolean b) {
try { try {
assertFalse(b); assertFalse(b);
} catch (AssertionFailedError t) { } catch (AssertionError fail) {
threadRecordFailure(t); threadRecordFailure(fail);
throw t; throw fail;
} }
} }
/** /**
* Just like assertNull(x), but additionally recording (using * Just like assertNull(x), but additionally recording (using
* threadRecordFailure) any AssertionFailedError thrown, so that * threadRecordFailure) any AssertionError thrown, so that the
* the current testcase will fail. * current testcase will fail.
*/ */
public void threadAssertNull(Object x) { public void threadAssertNull(Object x) {
try { try {
assertNull(x); assertNull(x);
} catch (AssertionFailedError t) { } catch (AssertionError fail) {
threadRecordFailure(t); threadRecordFailure(fail);
throw t; throw fail;
} }
} }
/** /**
* Just like assertEquals(x, y), but additionally recording (using * Just like assertEquals(x, y), but additionally recording (using
* threadRecordFailure) any AssertionFailedError thrown, so that * threadRecordFailure) any AssertionError thrown, so that the
* the current testcase will fail. * current testcase will fail.
*/ */
public void threadAssertEquals(long x, long y) { public void threadAssertEquals(long x, long y) {
try { try {
assertEquals(x, y); assertEquals(x, y);
} catch (AssertionFailedError t) { } catch (AssertionError fail) {
threadRecordFailure(t); threadRecordFailure(fail);
throw t; throw fail;
} }
} }
/** /**
* Just like assertEquals(x, y), but additionally recording (using * Just like assertEquals(x, y), but additionally recording (using
* threadRecordFailure) any AssertionFailedError thrown, so that * threadRecordFailure) any AssertionError thrown, so that the
* the current testcase will fail. * current testcase will fail.
*/ */
public void threadAssertEquals(Object x, Object y) { public void threadAssertEquals(Object x, Object y) {
try { try {
assertEquals(x, y); assertEquals(x, y);
} catch (AssertionFailedError fail) { } catch (AssertionError fail) {
threadRecordFailure(fail); threadRecordFailure(fail);
throw fail; throw fail;
} catch (Throwable fail) { } catch (Throwable fail) {
@ -906,13 +900,13 @@ public class JSR166TestCase extends TestCase {
/** /**
* Just like assertSame(x, y), but additionally recording (using * Just like assertSame(x, y), but additionally recording (using
* threadRecordFailure) any AssertionFailedError thrown, so that * threadRecordFailure) any AssertionError thrown, so that the
* the current testcase will fail. * current testcase will fail.
*/ */
public void threadAssertSame(Object x, Object y) { public void threadAssertSame(Object x, Object y) {
try { try {
assertSame(x, y); assertSame(x, y);
} catch (AssertionFailedError fail) { } catch (AssertionError fail) {
threadRecordFailure(fail); threadRecordFailure(fail);
throw fail; throw fail;
} }
@ -934,8 +928,8 @@ public class JSR166TestCase extends TestCase {
/** /**
* Records the given exception using {@link #threadRecordFailure}, * Records the given exception using {@link #threadRecordFailure},
* then rethrows the exception, wrapping it in an * then rethrows the exception, wrapping it in an AssertionError
* AssertionFailedError if necessary. * if necessary.
*/ */
public void threadUnexpectedException(Throwable t) { public void threadUnexpectedException(Throwable t) {
threadRecordFailure(t); threadRecordFailure(t);
@ -944,12 +938,8 @@ public class JSR166TestCase extends TestCase {
throw (RuntimeException) t; throw (RuntimeException) t;
else if (t instanceof Error) else if (t instanceof Error)
throw (Error) t; throw (Error) t;
else { else
AssertionFailedError afe = throw new AssertionError("unexpected exception: " + t, t);
new AssertionFailedError("unexpected exception: " + t);
afe.initCause(t);
throw afe;
}
} }
/** /**
@ -1125,7 +1115,7 @@ public class JSR166TestCase extends TestCase {
for (long retries = LONG_DELAY_MS * 3 / 4; retries-->0; ) { for (long retries = LONG_DELAY_MS * 3 / 4; retries-->0; ) {
try { delay(1); } try { delay(1); }
catch (InterruptedException fail) { catch (InterruptedException fail) {
fail("Unexpected InterruptedException"); throw new AssertionError("Unexpected InterruptedException", fail);
} }
Thread.State s = thread.getState(); Thread.State s = thread.getState();
if (s == expected) if (s == expected)
@ -1311,16 +1301,13 @@ public class JSR166TestCase extends TestCase {
/** /**
* Sleeps until the given time has elapsed. * Sleeps until the given time has elapsed.
* Throws AssertionFailedError if interrupted. * Throws AssertionError if interrupted.
*/ */
static void sleep(long millis) { static void sleep(long millis) {
try { try {
delay(millis); delay(millis);
} catch (InterruptedException fail) { } catch (InterruptedException fail) {
AssertionFailedError afe = throw new AssertionError("Unexpected InterruptedException", fail);
new AssertionFailedError("Unexpected InterruptedException");
afe.initCause(fail);
throw afe;
} }
} }
@ -1411,7 +1398,7 @@ public class JSR166TestCase extends TestCase {
// r.run(); // r.run();
// } catch (Throwable fail) { threadUnexpectedException(fail); } // } catch (Throwable fail) { threadUnexpectedException(fail); }
// if (millisElapsedSince(startTime) > timeoutMillis/2) // if (millisElapsedSince(startTime) > timeoutMillis/2)
// throw new AssertionFailedError("did not return promptly"); // throw new AssertionError("did not return promptly");
// } // }
// void assertTerminatesPromptly(Runnable r) { // void assertTerminatesPromptly(Runnable r) {
@ -1428,7 +1415,7 @@ public class JSR166TestCase extends TestCase {
assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS)); assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
} catch (Throwable fail) { threadUnexpectedException(fail); } } catch (Throwable fail) { threadUnexpectedException(fail); }
if (millisElapsedSince(startTime) > timeoutMillis/2) if (millisElapsedSince(startTime) > timeoutMillis/2)
throw new AssertionFailedError("timed get did not return promptly"); throw new AssertionError("timed get did not return promptly");
} }
<T> void checkTimedGet(Future<T> f, T expectedValue) { <T> void checkTimedGet(Future<T> f, T expectedValue) {
@ -1670,7 +1657,7 @@ public class JSR166TestCase extends TestCase {
// long startTime = System.nanoTime(); // long startTime = System.nanoTime();
// while (!flag.get()) { // while (!flag.get()) {
// if (millisElapsedSince(startTime) > timeoutMillis) // if (millisElapsedSince(startTime) > timeoutMillis)
// throw new AssertionFailedError("timed out"); // throw new AssertionError("timed out");
// Thread.yield(); // Thread.yield();
// } // }
// } // }
@ -1757,7 +1744,7 @@ public class JSR166TestCase extends TestCase {
/** /**
* A CyclicBarrier that uses timed await and fails with * A CyclicBarrier that uses timed await and fails with
* AssertionFailedErrors instead of throwing checked exceptions. * AssertionErrors instead of throwing checked exceptions.
*/ */
public static class CheckedBarrier extends CyclicBarrier { public static class CheckedBarrier extends CyclicBarrier {
public CheckedBarrier(int parties) { super(parties); } public CheckedBarrier(int parties) { super(parties); }
@ -1766,12 +1753,9 @@ public class JSR166TestCase extends TestCase {
try { try {
return super.await(2 * LONG_DELAY_MS, MILLISECONDS); return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
} catch (TimeoutException timedOut) { } catch (TimeoutException timedOut) {
throw new AssertionFailedError("timed out"); throw new AssertionError("timed out");
} catch (Exception fail) { } catch (Exception fail) {
AssertionFailedError afe = throw new AssertionError("Unexpected exception: " + fail, fail);
new AssertionFailedError("Unexpected exception: " + fail);
afe.initCause(fail);
throw afe;
} }
} }
} }
@ -1894,14 +1878,11 @@ public class JSR166TestCase extends TestCase {
try { throwingAction.run(); } try { throwingAction.run(); }
catch (Throwable t) { catch (Throwable t) {
threw = true; threw = true;
if (!expectedExceptionClass.isInstance(t)) { if (!expectedExceptionClass.isInstance(t))
AssertionFailedError afe = throw new AssertionError(
new AssertionFailedError "Expected " + expectedExceptionClass.getName() +
("Expected " + expectedExceptionClass.getName() + ", got " + t.getClass().getName(),
", got " + t.getClass().getName()); t);
afe.initCause(t);
threadUnexpectedException(afe);
}
} }
if (!threw) if (!threw)
shouldThrow(expectedExceptionClass.getName()); shouldThrow(expectedExceptionClass.getName());

View file

@ -69,7 +69,7 @@ public class LongAdderTest extends JSR166TestCase {
/** /**
* decrement decrements and sum returns current value * decrement decrements and sum returns current value
*/ */
public void testDecrementAndsum() { public void testDecrementAndSum() {
LongAdder ai = new LongAdder(); LongAdder ai = new LongAdder();
ai.decrement(); ai.decrement();
assertEquals(-1, ai.sum()); assertEquals(-1, ai.sum());
@ -80,7 +80,7 @@ public class LongAdderTest extends JSR166TestCase {
/** /**
* incrementAndGet increments and returns current value * incrementAndGet increments and returns current value
*/ */
public void testIncrementAndsum() { public void testIncrementAndSum() {
LongAdder ai = new LongAdder(); LongAdder ai = new LongAdder();
ai.increment(); ai.increment();
assertEquals(1, ai.sum()); assertEquals(1, ai.sum());

View file

@ -45,7 +45,6 @@ import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantLock;
import junit.framework.AssertionFailedError;
import junit.framework.Test; import junit.framework.Test;
import junit.framework.TestSuite; import junit.framework.TestSuite;
@ -115,7 +114,7 @@ public class ReentrantLockTest extends JSR166TestCase {
long startTime = System.nanoTime(); long startTime = System.nanoTime();
while (!lock.hasQueuedThread(t)) { while (!lock.hasQueuedThread(t)) {
if (millisElapsedSince(startTime) > LONG_DELAY_MS) if (millisElapsedSince(startTime) > LONG_DELAY_MS)
throw new AssertionFailedError("timed out"); throw new AssertionError("timed out");
Thread.yield(); Thread.yield();
} }
assertTrue(t.isAlive()); assertTrue(t.isAlive());

View file

@ -44,7 +44,6 @@ import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock;
import junit.framework.AssertionFailedError;
import junit.framework.Test; import junit.framework.Test;
import junit.framework.TestSuite; import junit.framework.TestSuite;
@ -115,7 +114,7 @@ public class ReentrantReadWriteLockTest extends JSR166TestCase {
long startTime = System.nanoTime(); long startTime = System.nanoTime();
while (!lock.hasQueuedThread(t)) { while (!lock.hasQueuedThread(t)) {
if (millisElapsedSince(startTime) > LONG_DELAY_MS) if (millisElapsedSince(startTime) > LONG_DELAY_MS)
throw new AssertionFailedError("timed out"); throw new AssertionError("timed out");
Thread.yield(); Thread.yield();
} }
assertTrue(t.isAlive()); assertTrue(t.isAlive());

View file

@ -40,7 +40,6 @@ import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore; import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.ThreadLocalRandom;
import junit.framework.AssertionFailedError;
import junit.framework.Test; import junit.framework.Test;
import junit.framework.TestSuite; import junit.framework.TestSuite;
@ -101,7 +100,7 @@ public class SemaphoreTest extends JSR166TestCase {
long startTime = System.nanoTime(); long startTime = System.nanoTime();
while (!s.hasQueuedThread(t)) { while (!s.hasQueuedThread(t)) {
if (millisElapsedSince(startTime) > LONG_DELAY_MS) if (millisElapsedSince(startTime) > LONG_DELAY_MS)
throw new AssertionFailedError("timed out"); throw new AssertionError("timed out");
Thread.yield(); Thread.yield();
} }
assertTrue(s.hasQueuedThreads()); assertTrue(s.hasQueuedThreads());
@ -115,7 +114,7 @@ public class SemaphoreTest extends JSR166TestCase {
long startTime = System.nanoTime(); long startTime = System.nanoTime();
while (!s.hasQueuedThreads()) { while (!s.hasQueuedThreads()) {
if (millisElapsedSince(startTime) > LONG_DELAY_MS) if (millisElapsedSince(startTime) > LONG_DELAY_MS)
throw new AssertionFailedError("timed out"); throw new AssertionError("timed out");
Thread.yield(); Thread.yield();
} }
} }

View file

@ -90,8 +90,7 @@ public class ThreadLocalRandomTest extends JSR166TestCase {
ThreadLocalRandom rnd = ThreadLocalRandom.current(); ThreadLocalRandom rnd = ThreadLocalRandom.current();
final java.lang.reflect.Method m; final java.lang.reflect.Method m;
try { try {
m = ThreadLocalRandom.class.getDeclaredMethod( m = ThreadLocalRandom.class.getDeclaredMethod("next", int.class);
"next", new Class[] { int.class });
m.setAccessible(true); m.setAccessible(true);
} catch (SecurityException acceptable) { } catch (SecurityException acceptable) {
// Security manager may deny access // Security manager may deny access