8142441: Improve jtreg tests for java.util.concurrent

Reviewed-by: martin, psandoz, chegar, shade, plevart
This commit is contained in:
Doug Lea 2015-11-25 18:56:44 -08:00
parent 4f79cf98f7
commit 9ea1a16abd
86 changed files with 1192 additions and 1127 deletions

View File

@ -146,25 +146,26 @@ public class CheckedSetBash {
ArrayList<Object[]> iters = new ArrayList<>(makeCheckedSets());
iters.ensureCapacity(numItr * iters.size());
for (int each=1; each < numItr; each++) {
iters.addAll( makeCheckedSets());
iters.addAll(makeCheckedSets());
}
return iters.iterator();
}
public static Collection<Object[]> makeCheckedSets() {
return Arrays.asList(
new Object[]{"Collections.checkedSet(HashSet)",
(Supplier) () -> {return Collections.checkedSet(new HashSet(), Integer.class);}},
new Object[]{"Collections.checkedSet(TreeSet(reverseOrder)",
(Supplier) () -> {return Collections.checkedSet(new TreeSet(Collections.reverseOrder()), Integer.class);}},
new Object[]{"Collections.checkedSet(TreeSet).descendingSet()",
(Supplier) () -> {return Collections.checkedSet(new TreeSet().descendingSet(), Integer.class);}},
new Object[]{"Collections.checkedNavigableSet(TreeSet)",
(Supplier) () -> {return Collections.checkedNavigableSet(new TreeSet(), Integer.class);}},
new Object[]{"Collections.checkedNavigableSet(TreeSet(reverseOrder)",
(Supplier) () -> {return Collections.checkedNavigableSet(new TreeSet(Collections.reverseOrder()), Integer.class);}},
new Object[]{"Collections.checkedNavigableSet().descendingSet()",
(Supplier) () -> {return Collections.checkedNavigableSet(new TreeSet().descendingSet(), Integer.class);}}
);
Object[][] params = {
{"Collections.checkedSet(HashSet)",
(Supplier) () -> Collections.checkedSet(new HashSet(), Integer.class)},
{"Collections.checkedSet(TreeSet(reverseOrder))",
(Supplier) () -> Collections.checkedSet(new TreeSet(Collections.reverseOrder()), Integer.class)},
{"Collections.checkedSet(TreeSet.descendingSet())",
(Supplier) () -> Collections.checkedSet(new TreeSet().descendingSet(), Integer.class)},
{"Collections.checkedNavigableSet(TreeSet)",
(Supplier) () -> Collections.checkedNavigableSet(new TreeSet(), Integer.class)},
{"Collections.checkedNavigableSet(TreeSet(reverseOrder))",
(Supplier) () -> Collections.checkedNavigableSet(new TreeSet(Collections.reverseOrder()), Integer.class)},
{"Collections.checkedNavigableSet(TreeSet.descendingSet())",
(Supplier) () -> Collections.checkedNavigableSet(new TreeSet().descendingSet(), Integer.class)},
};
return Arrays.asList(params);
}
}

View File

@ -58,7 +58,7 @@ public class EmptyCollectionSerialization {
Object singleton = o.get();
assertSame(o.get(), singleton, description + ": broken Supplier not returning singleton");
Object copy = patheticDeepCopy(singleton);
assertSame( copy, singleton, description + ": " +
assertSame(copy, singleton, description + ": " +
copy.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(copy)) +
" is not the singleton " +
singleton.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(singleton)));
@ -73,27 +73,28 @@ public class EmptyCollectionSerialization {
}
public static Collection<Object[]> makeSingletons() {
return Arrays.asList(
new Object[]{"Collections.EMPTY_LIST",
(Supplier) () -> {return Collections.EMPTY_LIST;}},
new Object[]{"Collections.EMPTY_MAP",
(Supplier) () -> {return Collections.EMPTY_MAP;}},
new Object[]{"Collections.EMPTY_SET",
(Supplier) () -> {return Collections.EMPTY_SET;}},
new Object[]{"Collections.singletonMap()",
(Supplier) () -> {return Collections.emptyList();}},
new Object[]{"Collections.emptyMap()",
(Supplier) () -> {return Collections.emptyMap();}},
new Object[]{"Collections.emptySet()",
(Supplier) () -> {return Collections.emptySet();}},
new Object[]{"Collections.emptySortedSet()",
(Supplier) () -> {return Collections.emptySortedSet();}},
new Object[]{"Collections.emptySortedMap()",
(Supplier) () -> {return Collections.emptySortedMap();}},
new Object[]{"Collections.emptyNavigableSet()",
(Supplier) () -> {return Collections.emptyNavigableSet();}},
new Object[]{"Collections.emptyNavigableMap()",
(Supplier) () -> {return Collections.emptyNavigableMap();}}
);
Object[][] params = {
{"Collections.EMPTY_LIST",
(Supplier) () -> Collections.EMPTY_LIST},
{"Collections.EMPTY_MAP",
(Supplier) () -> Collections.EMPTY_MAP},
{"Collections.EMPTY_SET",
(Supplier) () -> Collections.EMPTY_SET},
{"Collections.emptyList()",
(Supplier) () -> Collections.emptyList()},
{"Collections.emptyMap()",
(Supplier) () -> Collections.emptyMap()},
{"Collections.emptySet()",
(Supplier) () -> Collections.emptySet()},
{"Collections.emptySortedSet()",
(Supplier) () -> Collections.emptySortedSet()},
{"Collections.emptySortedMap()",
(Supplier) () -> Collections.emptySortedMap()},
{"Collections.emptyNavigableSet()",
(Supplier) () -> Collections.emptyNavigableSet()},
{"Collections.emptyNavigableMap()",
(Supplier) () -> Collections.emptyNavigableMap()},
};
return Arrays.asList(params);
}
}

View File

@ -202,9 +202,9 @@ public class SpliteratorLateBindingFailFastTest {
db.addCollection(PriorityQueue::new);
// ArrayDeque fails some tests since it's fail-fast support is weaker
// ArrayDeque fails some tests since its fail-fast support is weaker
// than other collections and limited to detecting most, but not all,
// removals. It probably requires it's own test since it is difficult
// removals. It probably requires its own test since it is difficult
// to abstract out the conditions under which it fails-fast.
// db.addCollection(ArrayDeque::new);

View File

@ -85,7 +85,7 @@ import static org.testng.Assert.assertEquals;
@Test
public class SpliteratorTraversingAndSplittingTest {
private static final List<Integer> SIZES = Arrays.asList(0, 1, 10, 100, 1000);
private static final List<Integer> SIZES = Arrays.asList(0, 1, 10, 42);
private static final String LOW = new String(new char[] {Character.MIN_LOW_SURROGATE});
private static final String HIGH = new String(new char[] {Character.MIN_HIGH_SURROGATE});

View File

@ -34,150 +34,148 @@
/*
* @test
* @bug 4486658
* @run main/timeout=7000 CancelledProducerConsumerLoops
* @summary Checks for responsiveness of blocking queues to cancellation.
* Runs under the assumption that ITERS computations require more than
* TIMEOUT msecs to complete.
*/
import java.util.concurrent.*;
import java.util.ArrayList;
import java.util.List;
import java.util.SplittableRandom;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;
public class CancelledProducerConsumerLoops {
static final int CAPACITY = 100;
static final long TIMEOUT = 100;
static final ExecutorService pool = Executors.newCachedThreadPool();
static boolean print = false;
static ExecutorService pool;
public static void main(String[] args) throws Exception {
int maxPairs = 8;
int iters = 1000000;
if (args.length > 0)
maxPairs = Integer.parseInt(args[0]);
print = true;
final int maxPairs = (args.length > 0) ? Integer.parseInt(args[0]) : 5;
pool = Executors.newCachedThreadPool();
for (int i = 1; i <= maxPairs; i += (i+1) >>> 1) {
System.out.println("Pairs:" + i);
try {
oneTest(i, iters);
}
catch (BrokenBarrierException bb) {
// OK, ignore
}
Thread.sleep(100);
final List<BlockingQueue<Integer>> queues = new ArrayList<>();
queues.add(new ArrayBlockingQueue<Integer>(100));
queues.add(new LinkedBlockingQueue<Integer>(100));
queues.add(new LinkedBlockingDeque<Integer>(100));
queues.add(new SynchronousQueue<Integer>());
// unbounded queue implementations are prone to OOME:
// PriorityBlockingQueue, LinkedTransferQueue
for (BlockingQueue<Integer> queue : queues)
new CancelledProducerConsumerLoops(i, queue).run();
}
pool.shutdown();
if (! pool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS))
throw new Error();
}
if (! pool.awaitTermination(10L, TimeUnit.SECONDS))
throw new AssertionError("timed out");
pool = null;
}
static void oneRun(BlockingQueue<Integer> q, int npairs, int iters) throws Exception {
if (print)
System.out.printf("%-18s", q.getClass().getSimpleName());
LoopHelpers.BarrierTimer timer = new LoopHelpers.BarrierTimer();
CyclicBarrier barrier = new CyclicBarrier(npairs * 2 + 1, timer);
final int npairs;
final BlockingQueue<Integer> queue;
final CountDownLatch producersInterrupted;
final CountDownLatch consumersInterrupted;
final LoopHelpers.BarrierTimer timer = new LoopHelpers.BarrierTimer();
final CyclicBarrier barrier;
final SplittableRandom rnd = new SplittableRandom();
volatile boolean done = false;
CancelledProducerConsumerLoops(int npairs, BlockingQueue<Integer> queue) {
this.npairs = npairs;
this.queue = queue;
this.producersInterrupted = new CountDownLatch(npairs - 1);
this.consumersInterrupted = new CountDownLatch(npairs - 1);
this.barrier = new CyclicBarrier(npairs * 2 + 1, timer);
}
void run() throws Exception {
Future<?>[] prods = new Future<?>[npairs];
Future<?>[] cons = new Future<?>[npairs];
for (int i = 0; i < npairs; ++i) {
prods[i] = pool.submit(new Producer(q, barrier, iters));
cons[i] = pool.submit(new Consumer(q, barrier, iters));
for (int i = 0; i < npairs; i++) {
prods[i] = pool.submit(new Producer());
cons[i] = pool.submit(new Consumer());
}
barrier.await();
Thread.sleep(TIMEOUT);
boolean tooLate = false;
Thread.sleep(rnd.nextInt(5));
for (int i = 1; i < npairs; ++i) {
if (!prods[i].cancel(true))
tooLate = true;
if (!cons[i].cancel(true))
tooLate = true;
for (int i = 1; i < npairs; i++) {
if (!prods[i].cancel(true) ||
!cons[i].cancel(true))
throw new AssertionError("completed before done");
}
Object p0 = prods[0].get();
Object c0 = cons[0].get();
if (!tooLate) {
for (int i = 1; i < npairs; ++i) {
if (!prods[i].isDone() || !prods[i].isCancelled())
throw new Error("Only one producer thread should complete");
if (!cons[i].isDone() || !cons[i].isCancelled())
throw new Error("Only one consumer thread should complete");
}
for (int i = 1; i < npairs; i++) {
assertCancelled(prods[i]);
assertCancelled(cons[i]);
}
else
System.out.print("(cancelled too late) ");
long endTime = System.nanoTime();
long time = endTime - timer.startTime;
if (print) {
double secs = (double)(time) / 1000000000.0;
System.out.println("\t " + secs + "s run time");
}
if (!producersInterrupted.await(10L, TimeUnit.SECONDS))
throw new AssertionError("timed out");
if (!consumersInterrupted.await(10L, TimeUnit.SECONDS))
throw new AssertionError("timed out");
if (prods[0].isDone() || prods[0].isCancelled())
throw new AssertionError("completed too early");
done = true;
if (! (prods[0].get(10L, TimeUnit.SECONDS) instanceof Integer))
throw new AssertionError("expected Integer");
if (! (cons[0].get(10L, TimeUnit.SECONDS) instanceof Integer))
throw new AssertionError("expected Integer");
}
static void oneTest(int pairs, int iters) throws Exception {
oneRun(new ArrayBlockingQueue<Integer>(CAPACITY), pairs, iters);
oneRun(new LinkedBlockingQueue<Integer>(CAPACITY), pairs, iters);
oneRun(new LinkedBlockingDeque<Integer>(CAPACITY), pairs, iters);
oneRun(new SynchronousQueue<Integer>(), pairs, iters / 8);
/* unbounded queue implementations are prone to OOME
oneRun(new PriorityBlockingQueue<Integer>(iters / 2 * pairs), pairs, iters / 4);
oneRun(new LinkedTransferQueue<Integer>(), pairs, iters);
*/
void assertCancelled(Future<?> future) throws Exception {
if (!future.isDone())
throw new AssertionError("not done");
if (!future.isCancelled())
throw new AssertionError("not cancelled");
try {
future.get(10L, TimeUnit.SECONDS);
throw new AssertionError("should throw CancellationException");
} catch (CancellationException success) {}
}
abstract static class Stage implements Callable<Integer> {
final BlockingQueue<Integer> queue;
final CyclicBarrier barrier;
final int iters;
Stage(BlockingQueue<Integer> q, CyclicBarrier b, int iters) {
queue = q;
barrier = b;
this.iters = iters;
}
}
static class Producer extends Stage {
Producer(BlockingQueue<Integer> q, CyclicBarrier b, int iters) {
super(q, b, iters);
}
class Producer implements Callable<Integer> {
public Integer call() throws Exception {
barrier.await();
int s = 0;
int l = 4321;
for (int i = 0; i < iters; ++i) {
l = LoopHelpers.compute1(l);
s += LoopHelpers.compute2(l);
if (!queue.offer(new Integer(l), 1, TimeUnit.SECONDS))
break;
int sum = 0;
try {
int x = 4321;
while (!done) {
if (Thread.interrupted()) throw new InterruptedException();
x = LoopHelpers.compute1(x);
sum += LoopHelpers.compute2(x);
queue.offer(new Integer(x), 1, TimeUnit.MILLISECONDS);
}
} catch (InterruptedException cancelled) {
producersInterrupted.countDown();
}
return new Integer(s);
return sum;
}
}
static class Consumer extends Stage {
Consumer(BlockingQueue<Integer> q, CyclicBarrier b, int iters) {
super(q, b, iters);
}
class Consumer implements Callable<Integer> {
public Integer call() throws Exception {
barrier.await();
int l = 0;
int s = 0;
for (int i = 0; i < iters; ++i) {
Integer x = queue.poll(1, TimeUnit.SECONDS);
if (x == null)
break;
l = LoopHelpers.compute1(x.intValue());
s += l;
int sum = 0;
try {
while (!done) {
Integer x = queue.poll(1, TimeUnit.MILLISECONDS);
if (x != null)
sum += LoopHelpers.compute1(x.intValue());
}
} catch (InterruptedException cancelled) {
consumersInterrupted.countDown();
}
return new Integer(s);
return sum;
}
}
}

View File

@ -37,8 +37,19 @@
* @summary Test drainTo failing due to c.add throwing
*/
import java.util.*;
import java.util.concurrent.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.FutureTask;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.RunnableScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
@SuppressWarnings({"unchecked", "rawtypes"})
public class DrainToFails {

View File

@ -28,9 +28,19 @@
* @author Martin Buchholz
*/
import java.util.*;
import java.util.concurrent.*;
import static java.util.concurrent.TimeUnit.*;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledThreadPoolExecutor;
public class Interrupt {
@ -61,7 +71,7 @@ public class Interrupt {
checkInterrupted0(fs, immediateExecutor);
checkInterrupted0(fs, delayedExecutor);
stpe.shutdown();
check(stpe.awaitTermination(10, SECONDS));
check(stpe.awaitTermination(10L, SECONDS));
}
static void testQueue(final BlockingQueue<Object> q) {

View File

@ -28,8 +28,13 @@
* @author Martin Buchholz
*/
import java.util.*;
import java.util.concurrent.*;
import java.util.Iterator;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.PriorityBlockingQueue;
public class LastElement {
void test(String[] args) throws Throwable {

View File

@ -31,13 +31,11 @@
* http://creativecommons.org/publicdomain/zero/1.0/
*/
import java.util.concurrent.atomic.AtomicLong;
/**
* Misc utilities in JSR166 performance tests
*/
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
class LoopHelpers {
// Some mindless computation to do between synchronizations...
@ -74,28 +72,6 @@ class LoopHelpers {
return x;
}
/**
* An actually useful random number generator, but unsynchronized.
* Basically same as java.util.Random.
*/
public static class SimpleRandom {
private static final long multiplier = 0x5DEECE66DL;
private static final long addend = 0xBL;
private static final long mask = (1L << 48) - 1;
static final AtomicLong seq = new AtomicLong(1);
private long seed = System.nanoTime() + seq.getAndIncrement();
public void setSeed(long s) {
seed = s;
}
public int next() {
long nextseed = (seed * multiplier + addend) & mask;
seed = nextseed;
return ((int)(nextseed >>> 17)) & 0x7FFFFFFF;
}
}
public static class BarrierTimer implements Runnable {
public volatile long startTime;
public volatile long endTime;

View File

@ -34,151 +34,124 @@
/*
* @test
* @bug 4486658
* @run main/timeout=3600 MultipleProducersSingleConsumerLoops
* @summary multiple producers and single consumer using blocking queues
*/
import java.util.concurrent.*;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.atomic.AtomicInteger;
public class MultipleProducersSingleConsumerLoops {
static final int CAPACITY = 100;
static final ExecutorService pool = Executors.newCachedThreadPool();
static boolean print = false;
static int producerSum;
static int consumerSum;
static synchronized void addProducerSum(int x) {
producerSum += x;
}
static synchronized void addConsumerSum(int x) {
consumerSum += x;
}
static synchronized void checkSum() {
if (producerSum != consumerSum)
throw new Error("CheckSum mismatch");
}
static ExecutorService pool;
public static void main(String[] args) throws Exception {
int maxProducers = 5;
int iters = 100000;
if (args.length > 0)
maxProducers = Integer.parseInt(args[0]);
print = false;
System.out.println("Warmup...");
oneTest(1, 10000);
Thread.sleep(100);
oneTest(2, 10000);
Thread.sleep(100);
print = true;
final int maxProducers = (args.length > 0)
? Integer.parseInt(args[0])
: 5;
pool = Executors.newCachedThreadPool();
for (int i = 1; i <= maxProducers; i += (i+1) >>> 1) {
System.out.println("----------------------------------------");
System.out.println("Producers:" + i);
oneTest(i, iters);
Thread.sleep(100);
// Adjust iterations to limit typical single runs to <= 10 ms;
// Notably, fair queues get fewer iters.
// Unbounded queues can legitimately OOME if iterations
// high enough, but we have a sufficiently low limit here.
run(new ArrayBlockingQueue<Integer>(100), i, 300);
run(new LinkedBlockingQueue<Integer>(100), i, 700);
run(new LinkedBlockingDeque<Integer>(100), i , 500);
run(new LinkedTransferQueue<Integer>(), i, 1000);
run(new PriorityBlockingQueue<Integer>(), i, 1000);
run(new SynchronousQueue<Integer>(), i, 500);
run(new SynchronousQueue<Integer>(true), i, 200);
run(new ArrayBlockingQueue<Integer>(100, true), i, 100);
}
pool.shutdown();
if (! pool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS))
if (! pool.awaitTermination(10L, SECONDS))
throw new Error();
}
static void oneTest(int producers, int iters) throws Exception {
oneRun(new ArrayBlockingQueue<Integer>(CAPACITY), producers, iters);
oneRun(new LinkedBlockingQueue<Integer>(CAPACITY), producers, iters);
oneRun(new LinkedBlockingDeque<Integer>(CAPACITY), producers, iters);
oneRun(new LinkedTransferQueue<Integer>(), producers, iters);
// Don't run PBQ since can legitimately run out of memory
// if (print)
// System.out.print("PriorityBlockingQueue ");
// oneRun(new PriorityBlockingQueue<Integer>(), producers, iters);
oneRun(new SynchronousQueue<Integer>(), producers, iters);
if (print)
System.out.println("fair implementations:");
oneRun(new SynchronousQueue<Integer>(true), producers, iters);
oneRun(new ArrayBlockingQueue<Integer>(CAPACITY, true), producers, iters);
pool = null;
}
abstract static class Stage implements Runnable {
final int iters;
final BlockingQueue<Integer> queue;
final CyclicBarrier barrier;
Stage(BlockingQueue<Integer> q, CyclicBarrier b, int iters) {
queue = q;
barrier = b;
this.iters = iters;
}
static void run(BlockingQueue<Integer> queue, int nproducers, int iters) throws Exception {
new MultipleProducersSingleConsumerLoops(queue, nproducers, iters).run();
}
static class Producer extends Stage {
Producer(BlockingQueue<Integer> q, CyclicBarrier b, int iters) {
super(q, b, iters);
}
final BlockingQueue<Integer> queue;
final int nproducers;
final int iters;
final LoopHelpers.BarrierTimer timer = new LoopHelpers.BarrierTimer();
final CyclicBarrier barrier;
final AtomicInteger checksum = new AtomicInteger(0);
Throwable fail;
public void run() {
try {
barrier.await();
int s = 0;
int l = hashCode();
for (int i = 0; i < iters; ++i) {
l = LoopHelpers.compute1(l);
l = LoopHelpers.compute2(l);
queue.put(new Integer(l));
s += l;
}
addProducerSum(s);
barrier.await();
}
catch (Exception ie) {
ie.printStackTrace();
return;
}
}
MultipleProducersSingleConsumerLoops(BlockingQueue<Integer> queue, int nproducers, int iters) {
this.queue = queue;
this.nproducers = nproducers;
this.iters = iters;
this.barrier = new CyclicBarrier(nproducers + 2, timer);
}
static class Consumer extends Stage {
Consumer(BlockingQueue<Integer> q, CyclicBarrier b, int iters) {
super(q, b, iters);
}
public void run() {
try {
barrier.await();
int s = 0;
for (int i = 0; i < iters; ++i) {
s += queue.take().intValue();
}
addConsumerSum(s);
barrier.await();
}
catch (Exception ie) {
ie.printStackTrace();
return;
}
}
}
static void oneRun(BlockingQueue<Integer> q, int nproducers, int iters) throws Exception {
if (print)
System.out.printf("%-18s", q.getClass().getSimpleName());
LoopHelpers.BarrierTimer timer = new LoopHelpers.BarrierTimer();
CyclicBarrier barrier = new CyclicBarrier(nproducers + 2, timer);
for (int i = 0; i < nproducers; ++i) {
pool.execute(new Producer(q, barrier, iters));
}
pool.execute(new Consumer(q, barrier, iters * nproducers));
void run() throws Exception {
for (int i = 0; i < nproducers; i++)
pool.execute(new Producer());
pool.execute(new Consumer());
barrier.await();
barrier.await();
long time = timer.getTime();
checkSum();
if (print)
System.out.println("\t: " + LoopHelpers.rightJustify(time / (iters * nproducers)) + " ns per transfer");
System.out.printf("%s, nproducers=%d: %d ms%n",
queue.getClass().getSimpleName(), nproducers,
NANOSECONDS.toMillis(timer.getTime()));
if (checksum.get() != 0) throw new AssertionError("checksum mismatch");
if (fail != null) throw new AssertionError(fail);
}
abstract class CheckedRunnable implements Runnable {
abstract void realRun() throws Throwable;
public final void run() {
try {
realRun();
} catch (Throwable t) {
fail = t;
t.printStackTrace();
throw new AssertionError(t);
}
}
}
class Producer extends CheckedRunnable {
void realRun() throws Throwable {
barrier.await();
int s = 0;
int l = hashCode();
for (int i = 0; i < iters; i++) {
l = LoopHelpers.compute1(l);
l = LoopHelpers.compute2(l);
queue.put(new Integer(l));
s += l;
}
checksum.getAndAdd(s);
barrier.await();
}
}
class Consumer extends CheckedRunnable {
void realRun() throws Throwable {
barrier.await();
int s = 0;
for (int i = 0; i < nproducers * iters; i++) {
s += queue.take().intValue();
}
checksum.getAndAdd(-s);
barrier.await();
}
}
}

View File

@ -34,13 +34,20 @@
/*
* @test
* @bug 6805775 6815766
* @run main OfferDrainToLoops 300
* @run main OfferDrainToLoops 100
* @summary Test concurrent offer vs. drainTo
*/
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.ArrayList;
import java.util.List;
import java.util.SplittableRandom;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.atomic.AtomicLong;
@SuppressWarnings({"unchecked", "rawtypes", "deprecation"})
public class OfferDrainToLoops {
@ -66,22 +73,22 @@ public class OfferDrainToLoops {
test(new LinkedTransferQueue());
}
Random getRandom() {
return ThreadLocalRandom.current();
}
void test(final BlockingQueue q) throws Throwable {
System.out.println(q.getClass().getSimpleName());
final long testDurationNanos = testDurationMillis * 1000L * 1000L;
final long quittingTimeNanos = System.nanoTime() + testDurationNanos;
final long timeoutMillis = 10L * 1000L;
final SplittableRandom rnd = new SplittableRandom();
/** Poor man's bounded buffer. */
final AtomicLong approximateCount = new AtomicLong(0L);
abstract class CheckedThread extends Thread {
CheckedThread(String name) {
final SplittableRandom rnd;
CheckedThread(String name, SplittableRandom rnd) {
super(name);
this.rnd = rnd;
setDaemon(true);
start();
}
@ -99,7 +106,7 @@ public class OfferDrainToLoops {
}
}
Thread offerer = new CheckedThread("offerer") {
Thread offerer = new CheckedThread("offerer", rnd.split()) {
protected void realRun() {
long c = 0;
for (long i = 0; ! quittingTime(i); i++) {
@ -113,9 +120,8 @@ public class OfferDrainToLoops {
Thread.yield();
}}}};
Thread drainer = new CheckedThread("drainer") {
Thread drainer = new CheckedThread("drainer", rnd.split()) {
protected void realRun() {
final Random rnd = getRandom();
while (! quittingTime()) {
List list = new ArrayList();
int n = rnd.nextBoolean() ?
@ -131,9 +137,8 @@ public class OfferDrainToLoops {
approximateCount.set(0); // Releases waiting offerer thread
}};
Thread scanner = new CheckedThread("scanner") {
Thread scanner = new CheckedThread("scanner", rnd.split()) {
protected void realRun() {
final Random rnd = getRandom();
while (! quittingTime()) {
switch (rnd.nextInt(3)) {
case 0: checkNotContainsNull(q); break;
@ -157,8 +162,6 @@ public class OfferDrainToLoops {
failed++;
for (StackTraceElement e : thread.getStackTrace())
System.err.println(e);
// Kludge alert
thread.stop();
thread.join(timeoutMillis);
}
}

View File

@ -40,7 +40,12 @@
* number of aborted timed waits occur without a signal.
*/
import java.util.concurrent.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;
public class PollMemoryLeak {
public static void main(String[] args) throws InterruptedException {

View File

@ -34,149 +34,126 @@
/*
* @test
* @bug 4486658
* @run main/timeout=3600 ProducerConsumerLoops
* @summary multiple producers and consumers using blocking queues
*/
import java.util.concurrent.*;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.atomic.AtomicInteger;
public class ProducerConsumerLoops {
static final int CAPACITY = 100;
static final ExecutorService pool = Executors.newCachedThreadPool();
static boolean print = false;
static int producerSum;
static int consumerSum;
static synchronized void addProducerSum(int x) {
producerSum += x;
}
static synchronized void addConsumerSum(int x) {
consumerSum += x;
}
static synchronized void checkSum() {
if (producerSum != consumerSum)
throw new Error("CheckSum mismatch");
}
static ExecutorService pool;
public static void main(String[] args) throws Exception {
int maxPairs = 8;
final int maxPairs = (args.length > 0)
? Integer.parseInt(args[0])
: 5;
int iters = 10000;
if (args.length > 0)
maxPairs = Integer.parseInt(args[0]);
print = false;
System.out.println("Warmup...");
oneTest(1, 10000);
Thread.sleep(100);
oneTest(2, 10000);
Thread.sleep(100);
print = true;
pool = Executors.newCachedThreadPool();
for (int i = 1; i <= maxPairs; i += (i+1) >>> 1) {
System.out.println("----------------------------------------");
System.out.println("Pairs: " + i);
oneTest(i, iters);
Thread.sleep(100);
// Adjust iterations to limit typical single runs to <= 10 ms;
// Notably, fair queues get fewer iters.
// Unbounded queues can legitimately OOME if iterations
// high enough, but we have a sufficiently low limit here.
run(new ArrayBlockingQueue<Integer>(100), i, 500);
run(new LinkedBlockingQueue<Integer>(100), i, 1000);
run(new LinkedBlockingDeque<Integer>(100), i, 1000);
run(new LinkedTransferQueue<Integer>(), i, 1000);
run(new PriorityBlockingQueue<Integer>(), i, 1000);
run(new SynchronousQueue<Integer>(), i, 400);
run(new SynchronousQueue<Integer>(true), i, 300);
run(new ArrayBlockingQueue<Integer>(100, true), i, 100);
}
pool.shutdown();
if (! pool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS))
if (! pool.awaitTermination(60L, SECONDS))
throw new Error();
pool = null;
}
static void oneTest(int pairs, int iters) throws Exception {
oneRun(new ArrayBlockingQueue<Integer>(CAPACITY), pairs, iters);
oneRun(new LinkedBlockingQueue<Integer>(CAPACITY), pairs, iters);
oneRun(new LinkedBlockingDeque<Integer>(CAPACITY), pairs, iters);
oneRun(new LinkedTransferQueue<Integer>(), pairs, iters);
oneRun(new PriorityBlockingQueue<Integer>(), pairs, iters);
oneRun(new SynchronousQueue<Integer>(), pairs, iters);
if (print)
System.out.println("fair implementations:");
oneRun(new SynchronousQueue<Integer>(true), pairs, iters);
oneRun(new ArrayBlockingQueue<Integer>(CAPACITY, true), pairs, iters);
static void run(BlockingQueue<Integer> queue, int pairs, int iters) throws Exception {
new ProducerConsumerLoops(queue, pairs, iters).run();
}
abstract static class Stage implements Runnable {
final int iters;
final BlockingQueue<Integer> queue;
final CyclicBarrier barrier;
Stage(BlockingQueue<Integer> q, CyclicBarrier b, int iters) {
queue = q;
barrier = b;
this.iters = iters;
}
final BlockingQueue<Integer> queue;
final int pairs;
final int iters;
final LoopHelpers.BarrierTimer timer = new LoopHelpers.BarrierTimer();
final CyclicBarrier barrier;
final AtomicInteger checksum = new AtomicInteger(0);
Throwable fail;
ProducerConsumerLoops(BlockingQueue<Integer> queue, int pairs, int iters) {
this.queue = queue;
this.pairs = pairs;
this.iters = iters;
this.barrier = new CyclicBarrier(2 * pairs + 1, timer);
}
static class Producer extends Stage {
Producer(BlockingQueue<Integer> q, CyclicBarrier b, int iters) {
super(q, b, iters);
}
public void run() {
try {
barrier.await();
int s = 0;
int l = hashCode();
for (int i = 0; i < iters; ++i) {
l = LoopHelpers.compute2(l);
queue.put(new Integer(l));
s += LoopHelpers.compute1(l);
}
addProducerSum(s);
barrier.await();
}
catch (Exception ie) {
ie.printStackTrace();
return;
}
}
}
static class Consumer extends Stage {
Consumer(BlockingQueue<Integer> q, CyclicBarrier b, int iters) {
super(q, b, iters);
}
public void run() {
try {
barrier.await();
int l = 0;
int s = 0;
for (int i = 0; i < iters; ++i) {
l = LoopHelpers.compute1(queue.take().intValue());
s += l;
}
addConsumerSum(s);
barrier.await();
}
catch (Exception ie) {
ie.printStackTrace();
return;
}
}
}
static void oneRun(BlockingQueue<Integer> q, int npairs, int iters) throws Exception {
if (print)
System.out.printf("%-18s", q.getClass().getSimpleName());
LoopHelpers.BarrierTimer timer = new LoopHelpers.BarrierTimer();
CyclicBarrier barrier = new CyclicBarrier(npairs * 2 + 1, timer);
for (int i = 0; i < npairs; ++i) {
pool.execute(new Producer(q, barrier, iters));
pool.execute(new Consumer(q, barrier, iters));
void run() throws Exception {
for (int i = 0; i < pairs; i++) {
pool.execute(new Producer());
pool.execute(new Consumer());
}
barrier.await();
barrier.await();
long time = timer.getTime();
checkSum();
if (print)
System.out.println("\t: " + LoopHelpers.rightJustify(time / (iters * npairs)) + " ns per transfer");
System.out.printf("%s, pairs=%d: %d ms%n",
queue.getClass().getSimpleName(), pairs,
NANOSECONDS.toMillis(timer.getTime()));
if (checksum.get() != 0) throw new AssertionError("checksum mismatch");
if (fail != null) throw new AssertionError(fail);
}
abstract class CheckedRunnable implements Runnable {
abstract void realRun() throws Throwable;
public final void run() {
try {
realRun();
} catch (Throwable t) {
fail = t;
t.printStackTrace();
throw new AssertionError(t);
}
}
}
class Producer extends CheckedRunnable {
void realRun() throws Throwable {
barrier.await();
int s = 0;
int l = hashCode();
for (int i = 0; i < iters; i++) {
l = LoopHelpers.compute2(l);
queue.put(new Integer(l));
s += LoopHelpers.compute1(l);
}
checksum.getAndAdd(s);
barrier.await();
}
}
class Consumer extends CheckedRunnable {
void realRun() throws Throwable {
barrier.await();
int l = 0;
int s = 0;
for (int i = 0; i < iters; i++) {
l = LoopHelpers.compute1(queue.take().intValue());
s += l;
}
checksum.getAndAdd(-s);
barrier.await();
}
}
}

View File

@ -34,135 +34,126 @@
/*
* @test
* @bug 4486658
* @run main/timeout=600 SingleProducerMultipleConsumerLoops
* @summary check ordering for blocking queues with 1 producer and multiple consumers
*/
import java.util.concurrent.*;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.SynchronousQueue;
public class SingleProducerMultipleConsumerLoops {
static final int CAPACITY = 100;
static final ExecutorService pool = Executors.newCachedThreadPool();
static boolean print = false;
static ExecutorService pool;
public static void main(String[] args) throws Exception {
int maxConsumers = 5;
int iters = 10000;
if (args.length > 0)
maxConsumers = Integer.parseInt(args[0]);
print = false;
System.out.println("Warmup...");
oneTest(1, 10000);
Thread.sleep(100);
oneTest(2, 10000);
Thread.sleep(100);
print = true;
final int maxConsumers = (args.length > 0)
? Integer.parseInt(args[0])
: 5;
pool = Executors.newCachedThreadPool();
for (int i = 1; i <= maxConsumers; i += (i+1) >>> 1) {
System.out.println("----------------------------------------");
System.out.println("Consumers: " + i);
oneTest(i, iters);
Thread.sleep(100);
// Adjust iterations to limit typical single runs to <= 10 ms;
// Notably, fair queues get fewer iters.
// Unbounded queues can legitimately OOME if iterations
// high enough, but we have a sufficiently low limit here.
run(new ArrayBlockingQueue<Integer>(100), i, 1000);
run(new LinkedBlockingQueue<Integer>(100), i, 1000);
run(new LinkedBlockingDeque<Integer>(100), i, 1000);
run(new LinkedTransferQueue<Integer>(), i, 700);
run(new PriorityBlockingQueue<Integer>(), i, 1000);
run(new SynchronousQueue<Integer>(), i, 300);
run(new SynchronousQueue<Integer>(true), i, 200);
run(new ArrayBlockingQueue<Integer>(100, true), i, 100);
}
pool.shutdown();
if (! pool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS))
if (! pool.awaitTermination(60L, SECONDS))
throw new Error();
pool = null;
}
static void oneTest(int consumers, int iters) throws Exception {
oneRun(new ArrayBlockingQueue<Integer>(CAPACITY), consumers, iters);
oneRun(new LinkedBlockingQueue<Integer>(CAPACITY), consumers, iters);
oneRun(new LinkedBlockingDeque<Integer>(CAPACITY), consumers, iters);
oneRun(new LinkedTransferQueue<Integer>(), consumers, iters);
oneRun(new PriorityBlockingQueue<Integer>(), consumers, iters);
oneRun(new SynchronousQueue<Integer>(), consumers, iters);
if (print)
System.out.println("fair implementations:");
oneRun(new SynchronousQueue<Integer>(true), consumers, iters);
oneRun(new ArrayBlockingQueue<Integer>(CAPACITY, true), consumers, iters);
static void run(BlockingQueue<Integer> queue, int consumers, int iters) throws Exception {
new SingleProducerMultipleConsumerLoops(queue, consumers, iters).run();
}
abstract static class Stage implements Runnable {
final int iters;
final BlockingQueue<Integer> queue;
final CyclicBarrier barrier;
final BlockingQueue<Integer> queue;
final int consumers;
final int iters;
final LoopHelpers.BarrierTimer timer = new LoopHelpers.BarrierTimer();
final CyclicBarrier barrier;
Throwable fail;
SingleProducerMultipleConsumerLoops(BlockingQueue<Integer> queue, int consumers, int iters) {
this.queue = queue;
this.consumers = consumers;
this.iters = iters;
this.barrier = new CyclicBarrier(consumers + 2, timer);
}
void run() throws Exception {
pool.execute(new Producer());
for (int i = 0; i < consumers; i++) {
pool.execute(new Consumer());
}
barrier.await();
barrier.await();
System.out.printf("%s, consumers=%d: %d ms%n",
queue.getClass().getSimpleName(), consumers,
NANOSECONDS.toMillis(timer.getTime()));
if (fail != null) throw new AssertionError(fail);
}
abstract class CheckedRunnable implements Runnable {
abstract void realRun() throws Throwable;
public final void run() {
try {
realRun();
} catch (Throwable t) {
fail = t;
t.printStackTrace();
throw new AssertionError(t);
}
}
}
class Producer extends CheckedRunnable {
volatile int result;
Stage(BlockingQueue<Integer> q, CyclicBarrier b, int iters) {
queue = q;
barrier = b;
this.iters = iters;
void realRun() throws Throwable {
barrier.await();
for (int i = 0; i < iters * consumers; i++) {
queue.put(new Integer(i));
}
barrier.await();
result = 432;
}
}
static class Producer extends Stage {
Producer(BlockingQueue<Integer> q, CyclicBarrier b, int iters) {
super(q, b, iters);
}
public void run() {
try {
barrier.await();
for (int i = 0; i < iters; ++i) {
queue.put(new Integer(i));
}
barrier.await();
result = 432;
}
catch (Exception ie) {
ie.printStackTrace();
return;
class Consumer extends CheckedRunnable {
volatile int result;
void realRun() throws Throwable {
barrier.await();
int l = 0;
int s = 0;
int last = -1;
for (int i = 0; i < iters; i++) {
Integer item = queue.take();
int v = item.intValue();
if (v < last)
throw new Error("Out-of-Order transfer");
last = v;
l = LoopHelpers.compute1(v);
s += l;
}
barrier.await();
result = s;
}
}
static class Consumer extends Stage {
Consumer(BlockingQueue<Integer> q, CyclicBarrier b, int iters) {
super(q, b, iters);
}
public void run() {
try {
barrier.await();
int l = 0;
int s = 0;
int last = -1;
for (int i = 0; i < iters; ++i) {
Integer item = queue.take();
int v = item.intValue();
if (v < last)
throw new Error("Out-of-Order transfer");
last = v;
l = LoopHelpers.compute1(v);
s += l;
}
barrier.await();
result = s;
}
catch (Exception ie) {
ie.printStackTrace();
return;
}
}
}
static void oneRun(BlockingQueue<Integer> q, int nconsumers, int iters) throws Exception {
if (print)
System.out.printf("%-18s", q.getClass().getSimpleName());
LoopHelpers.BarrierTimer timer = new LoopHelpers.BarrierTimer();
CyclicBarrier barrier = new CyclicBarrier(nconsumers + 2, timer);
pool.execute(new Producer(q, barrier, iters * nconsumers));
for (int i = 0; i < nconsumers; ++i) {
pool.execute(new Consumer(q, barrier, iters));
}
barrier.await();
barrier.await();
long time = timer.getTime();
if (print)
System.out.println("\t: " + LoopHelpers.rightJustify(time / (iters * nconsumers)) + " ns per transfer");
}
}

View File

@ -40,17 +40,19 @@
* @author Chris Hegarty
*/
import static java.util.concurrent.CompletableFuture.runAsync;
import static java.util.concurrent.CompletableFuture.supplyAsync;
import static java.util.concurrent.ForkJoinPool.commonPool;
import static java.util.concurrent.TimeUnit.SECONDS;
import java.lang.reflect.Array;
import java.util.concurrent.Phaser;
import static java.util.concurrent.TimeUnit.*;
import java.util.concurrent.CompletableFuture;
import static java.util.concurrent.CompletableFuture.*;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static java.util.concurrent.ForkJoinPool.*;
import java.util.concurrent.atomic.AtomicInteger;
public class Basic {
@ -112,7 +114,7 @@ public class Basic {
test(executor);
} finally {
executor.shutdown();
executor.awaitTermination(30, SECONDS);
executor.awaitTermination(30L, SECONDS);
}
}

View File

@ -31,13 +31,11 @@
* http://creativecommons.org/publicdomain/zero/1.0/
*/
import java.util.concurrent.atomic.AtomicLong;
/**
* Misc utilities in JSR166 performance tests
*/
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
class LoopHelpers {
// Some mindless computation to do between synchronizations...
@ -74,28 +72,6 @@ class LoopHelpers {
return x;
}
/**
* An actually useful random number generator, but unsynchronized.
* Basically same as java.util.Random.
*/
public static class SimpleRandom {
private static final long multiplier = 0x5DEECE66DL;
private static final long addend = 0xBL;
private static final long mask = (1L << 48) - 1;
static final AtomicLong seq = new AtomicLong(1);
private long seed = System.nanoTime() + seq.getAndIncrement();
public void setSeed(long s) {
seed = s;
}
public int next() {
long nextseed = (seed * multiplier + addend) & mask;
seed = nextseed;
return ((int)(nextseed >>> 17)) & 0x7FFFFFFF;
}
}
public static class BarrierTimer implements Runnable {
public volatile long startTime;
public volatile long endTime;

View File

@ -38,8 +38,20 @@
* @summary Times and checks basic map operations
*/
import java.util.*;
import java.io.*;
import java.io.Serializable;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SplittableRandom;
public class MapCheck {
@ -599,12 +611,11 @@ public class MapCheck {
Stats(double t) { least = t; }
}
static Random rng = new Random();
static void shuffle(Object[] keys) {
SplittableRandom rnd = new SplittableRandom();
int size = keys.length;
for (int i=size; i>1; i--) {
int r = rng.nextInt(i);
int r = rnd.nextInt(i);
Object t = keys[i-1];
keys[i-1] = keys[r];
keys[r] = t;

View File

@ -44,15 +44,22 @@
* parsing from command line.)
*/
import java.util.*;
import java.util.concurrent.*;
import static java.util.concurrent.TimeUnit.SECONDS;
import java.util.List;
import java.util.Map;
import java.util.SplittableRandom;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MapLoops {
static int nkeys = 10000;
static int nkeys = 1000; // 10_000
static int pinsert = 60;
static int premove = 2;
static int maxThreads = 100;
static int nops = 100000;
static int nops = 10000; // 100_000
static int removesPerMaxRandom;
static int insertsPerMaxRandom;
@ -104,7 +111,6 @@ public class MapLoops {
int k = 1;
int warmups = 2;
for (int i = 1; i <= maxThreads;) {
Thread.sleep(100);
test(i, nkeys, mapClass);
if (warmups > 0)
--warmups;
@ -120,7 +126,7 @@ public class MapLoops {
i = k;
}
pool.shutdown();
if (! pool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS))
if (! pool.awaitTermination(60L, SECONDS))
throw new Error();
if (! throwables.isEmpty())
@ -129,17 +135,17 @@ public class MapLoops {
}
static Integer[] makeKeys(int n) {
LoopHelpers.SimpleRandom rng = new LoopHelpers.SimpleRandom();
SplittableRandom rnd = new SplittableRandom();
Integer[] key = new Integer[n];
for (int i = 0; i < key.length; ++i)
key[i] = new Integer(rng.next());
key[i] = new Integer(rnd.nextInt());
return key;
}
static void shuffleKeys(Integer[] key) {
Random rng = new Random();
SplittableRandom rnd = new SplittableRandom();
for (int i = key.length; i > 1; --i) {
int j = rng.nextInt(i);
int j = rnd.nextInt(i);
Integer tmp = key[j];
key[j] = key[i-1];
key[i-1] = tmp;
@ -155,8 +161,9 @@ public class MapLoops {
// map.put(key[j], key[j]);
LoopHelpers.BarrierTimer timer = new LoopHelpers.BarrierTimer();
CyclicBarrier barrier = new CyclicBarrier(i+1, timer);
SplittableRandom rnd = new SplittableRandom();
for (int t = 0; t < i; ++t)
pool.execute(new Runner(map, key, barrier));
pool.execute(new Runner(map, key, barrier, rnd.split()));
barrier.await();
barrier.await();
long time = timer.getTime();
@ -170,21 +177,25 @@ public class MapLoops {
static class Runner implements Runnable {
final Map<Integer,Integer> map;
final Integer[] key;
final LoopHelpers.SimpleRandom rng = new LoopHelpers.SimpleRandom();
final CyclicBarrier barrier;
final SplittableRandom rnd;
int position;
int total;
Runner(Map<Integer,Integer> map, Integer[] key, CyclicBarrier barrier) {
Runner(Map<Integer,Integer> map,
Integer[] key,
CyclicBarrier barrier,
SplittableRandom rnd) {
this.map = map;
this.key = key;
this.barrier = barrier;
this.rnd = rnd;
position = key.length / 2;
}
int step() {
// random-walk around key positions, bunching accesses
int r = rng.next();
int r = rnd.nextInt(Integer.MAX_VALUE);
position += (r & 7) - 3;
while (position >= key.length) position -= key.length;
while (position < 0) position += key.length;

View File

@ -27,8 +27,11 @@
* @summary Reasonable things should happen if mutating while iterating.
*/
import java.util.*;
import java.util.concurrent.*;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ConcurrentSkipListMap;
public class ConcurrentModification {
static volatile int passed = 0, failed = 0;

View File

@ -38,9 +38,25 @@
* @summary Checks that a set of threads can repeatedly get and modify items
*/
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import static java.util.concurrent.TimeUnit.SECONDS;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.atomic.AtomicInteger;
public class ConcurrentQueueLoops {
ExecutorService pool;
@ -99,7 +115,7 @@ public class ConcurrentQueueLoops {
oneRun(i, items, q);
}
pool.shutdown();
check(pool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS));
check(pool.awaitTermination(60L, SECONDS));
}
class Stage implements Callable<Integer> {

View File

@ -31,15 +31,28 @@
* http://creativecommons.org/publicdomain/zero/1.0/
*/
import java.util.*;
import java.util.concurrent.*;
/*
* @test
* @bug 6805775 6815766
* @summary Check weak consistency of concurrent queue iterators
*/
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Queue;
import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.LinkedTransferQueue;
@SuppressWarnings({"unchecked", "rawtypes"})
public class IteratorWeakConsistency {
final Random rnd = new Random();

View File

@ -31,13 +31,11 @@
* http://creativecommons.org/publicdomain/zero/1.0/
*/
import java.util.concurrent.atomic.AtomicLong;
/**
* Misc utilities in JSR166 performance tests
*/
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
class LoopHelpers {
// Some mindless computation to do between synchronizations...
@ -74,28 +72,6 @@ class LoopHelpers {
return x;
}
/**
* An actually useful random number generator, but unsynchronized.
* Basically same as java.util.Random.
*/
public static class SimpleRandom {
private static final long multiplier = 0x5DEECE66DL;
private static final long addend = 0xBL;
private static final long mask = (1L << 48) - 1;
static final AtomicLong seq = new AtomicLong(1);
private long seed = System.nanoTime() + seq.getAndIncrement();
public void setSeed(long s) {
seed = s;
}
public int next() {
long nextseed = (seed * multiplier + addend) & mask;
seed = nextseed;
return ((int)(nextseed >>> 17)) & 0x7FFFFFFF;
}
}
public static class BarrierTimer implements Runnable {
public volatile long startTime;
public volatile long endTime;

View File

@ -29,10 +29,21 @@
* @author Martin Buchholz
*/
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import static java.util.concurrent.TimeUnit.*;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import java.util.Arrays;
import java.util.Queue;
import java.util.SplittableRandom;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadLocalRandom;
@SuppressWarnings({"unchecked", "rawtypes", "deprecation"})
public class OfferRemoveLoops {
@ -61,10 +72,6 @@ public class OfferRemoveLoops {
testQueue(new LinkedTransferQueue());
}
Random getRandom() {
return ThreadLocalRandom.current();
}
void testQueue(final Queue q) throws Throwable {
System.err.println(q.getClass().getSimpleName());
final long testDurationNanos = testDurationMillis * 1000L * 1000L;
@ -73,13 +80,17 @@ public class OfferRemoveLoops {
final int maxChunkSize = 1042;
final int maxQueueSize = 10 * maxChunkSize;
final CountDownLatch done = new CountDownLatch(3);
final SplittableRandom rnd = new SplittableRandom();
/** Poor man's bounded buffer; prevents unbounded queue expansion. */
final Semaphore offers = new Semaphore(maxQueueSize);
abstract class CheckedThread extends Thread {
CheckedThread(String name) {
final SplittableRandom rnd;
CheckedThread(String name, SplittableRandom rnd) {
super(name);
this.rnd = rnd;
setDaemon(true);
start();
}
@ -97,9 +108,9 @@ public class OfferRemoveLoops {
}
}
Thread offerer = new CheckedThread("offerer") {
Thread offerer = new CheckedThread("offerer", rnd.split()) {
protected void realRun() throws InterruptedException {
final int chunkSize = getRandom().nextInt(maxChunkSize) + 20;
final int chunkSize = rnd.nextInt(maxChunkSize) + 20;
long c = 0;
while (! quittingTime()) {
if (q.offer(Long.valueOf(c))) {
@ -113,9 +124,9 @@ public class OfferRemoveLoops {
done.countDown();
}};
Thread remover = new CheckedThread("remover") {
Thread remover = new CheckedThread("remover", rnd.split()) {
protected void realRun() {
final int chunkSize = getRandom().nextInt(maxChunkSize) + 20;
final int chunkSize = rnd.nextInt(maxChunkSize) + 20;
long c = 0;
while (! quittingTime()) {
if (q.remove(Long.valueOf(c))) {
@ -131,9 +142,8 @@ public class OfferRemoveLoops {
done.countDown();
}};
Thread scanner = new CheckedThread("scanner") {
Thread scanner = new CheckedThread("scanner", rnd.split()) {
protected void realRun() {
final Random rnd = getRandom();
while (! quittingTime()) {
switch (rnd.nextInt(3)) {
case 0: checkNotContainsNull(q); break;

View File

@ -26,6 +26,7 @@
* @bug 8011645
* @summary CopyOnWriteArrayList.COWSubList.subList does not validate range properly
*/
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

View File

@ -28,8 +28,10 @@
* @author Martin Buchholz
*/
import java.util.*;
import java.util.concurrent.*;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
public class EqualsRace {
private static void realMain(String[] args) throws Throwable {

View File

@ -28,8 +28,10 @@
* @author Martin Buchholz
*/
import java.util.*;
import java.util.concurrent.*;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;
public class RacingCows {
private static void realMain(String[] args) throws Throwable {

View File

@ -28,7 +28,8 @@
* @author Seetharam Avadhanam, Martin Buchholz
*/
import java.util.concurrent.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
interface AwaiterFactory {

View File

@ -28,10 +28,17 @@
* @author Martin Buchholz, David Holmes
*/
import java.util.*;
import java.util.concurrent.*;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import static java.util.concurrent.TimeUnit.*;
public class Basic {

View File

@ -28,9 +28,11 @@
* @author Martin Buchholz
*/
import java.io.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.Arrays;
import java.util.Iterator;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
public class Iterate {
private static class Godot implements Delayed {

View File

@ -28,7 +28,9 @@
* @author Martin Buchholz
*/
import java.util.concurrent.*;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
public class PollUnexpired {
private static class Godot implements Delayed {

View File

@ -21,8 +21,11 @@
* questions.
*/
import java.util.concurrent.*;
import static java.util.concurrent.TimeUnit.*;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
/**
* This is not a regression test, but a stress benchmark test for

View File

@ -38,7 +38,12 @@
* @summary checks to make sure a pipeline of exchangers passes data.
*/
import java.util.concurrent.*;
import static java.util.concurrent.TimeUnit.SECONDS;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ExchangeLoops {
static final ExecutorService pool = Executors.newCachedThreadPool();
@ -66,7 +71,7 @@ public class ExchangeLoops {
oneRun(i, iters);
}
pool.shutdown();
if (! pool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS))
if (! pool.awaitTermination(60L, SECONDS))
throw new Error();
}

View File

@ -30,13 +30,12 @@
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/publicdomain/zero/1.0/
*/
import java.util.concurrent.atomic.AtomicLong;
/**
* Misc utilities in JSR166 performance tests
*/
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
class LoopHelpers {
// Some mindless computation to do between synchronizations...
@ -73,28 +72,6 @@ class LoopHelpers {
return x;
}
/**
* An actually useful random number generator, but unsynchronized.
* Basically same as java.util.Random.
*/
public static class SimpleRandom {
private static final long multiplier = 0x5DEECE66DL;
private static final long addend = 0xBL;
private static final long mask = (1L << 48) - 1;
static final AtomicLong seq = new AtomicLong(1);
private long seed = System.nanoTime() + seq.getAndIncrement();
public void setSeed(long s) {
seed = s;
}
public int next() {
long nextseed = (seed * multiplier + addend) & mask;
seed = nextseed;
return ((int)(nextseed >>> 17)) & 0x7FFFFFFF;
}
}
public static class BarrierTimer implements Runnable {
public volatile long startTime;
public volatile long endTime;

View File

@ -38,10 +38,15 @@
* @summary Exercise ExecutorCompletionServiceLoops
*/
import java.util.concurrent.*;
import static java.util.concurrent.TimeUnit.SECONDS;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ExecutorCompletionServiceLoops {
static final int POOLSIZE = 100;
static final int POOLSIZE = 100;
static final ExecutorService pool =
Executors.newFixedThreadPool(POOLSIZE);
static final ExecutorCompletionService<Integer> ecs =
@ -66,7 +71,7 @@ public class ExecutorCompletionServiceLoops {
Thread.sleep(100);
}
pool.shutdown();
if (! pool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS))
if (! pool.awaitTermination(60L, SECONDS))
throw new Error();
}

View File

@ -30,13 +30,12 @@
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/publicdomain/zero/1.0/
*/
import java.util.concurrent.atomic.AtomicLong;
/**
* Misc utilities in JSR166 performance tests
*/
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
class LoopHelpers {
// Some mindless computation to do between synchronizations...
@ -73,28 +72,6 @@ class LoopHelpers {
return x;
}
/**
* An actually useful random number generator, but unsynchronized.
* Basically same as java.util.Random.
*/
public static class SimpleRandom {
private static final long multiplier = 0x5DEECE66DL;
private static final long addend = 0xBL;
private static final long mask = (1L << 48) - 1;
static final AtomicLong seq = new AtomicLong(1);
private long seed = System.nanoTime() + seq.getAndIncrement();
public void setSeed(long s) {
seed = s;
}
public int next() {
long nextseed = (seed * multiplier + addend) & mask;
seed = nextseed;
return ((int)(nextseed >>> 17)) & 0x7FFFFFFF;
}
}
public static class BarrierTimer implements Runnable {
public volatile long startTime;
public volatile long endTime;

View File

@ -28,9 +28,13 @@
* @author Martin Buchholz
*/
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicLong;
public class Invoke {
static volatile int passed = 0, failed = 0;

View File

@ -29,10 +29,18 @@
* @author Martin Buchholz
*/
import java.util.concurrent.*;
import java.util.*;
import java.security.*;
import static java.util.concurrent.Executors.*;
import static java.util.concurrent.Executors.privilegedCallable;
import static java.util.concurrent.Executors.privilegedCallableUsingCurrentClassLoader;
import static java.util.concurrent.Executors.privilegedThreadFactory;
import java.security.AccessControlException;
import java.security.CodeSource;
import java.security.Permission;
import java.security.PermissionCollection;
import java.security.Permissions;
import java.security.ProtectionDomain;
import java.util.Random;
import java.util.concurrent.Callable;
public class PrivilegedCallables {
Callable<Integer> real;
@ -44,7 +52,7 @@ public class PrivilegedCallables {
final Random rnd = new Random();
@SuppressWarnings("serial")
Throwable[] throwables = {
final Throwable[] throwables = {
new Exception() {},
new RuntimeException() {},
new Error() {}

View File

@ -28,12 +28,24 @@
* @author Martin Buchholz
*/
import java.io.*;
import java.util.*;
import java.util.concurrent.*;
import static java.util.concurrent.Executors.*;
import static java.util.concurrent.Executors.callable;
import static java.util.concurrent.Executors.defaultThreadFactory;
import static java.util.concurrent.Executors.newCachedThreadPool;
import static java.util.concurrent.Executors.newFixedThreadPool;
import static java.util.concurrent.Executors.newScheduledThreadPool;
import static java.util.concurrent.Executors.newSingleThreadExecutor;
import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
import static java.util.concurrent.Executors.privilegedCallable;
import static java.util.concurrent.Executors.unconfigurableExecutorService;
import static java.util.concurrent.Executors.unconfigurableScheduledExecutorService;
import java.security.PrivilegedAction;
import java.security.PrivilegedExceptionAction;
import java.util.concurrent.Callable;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
public class Throws {
private static void realMain(String[] args) throws Throwable {

View File

@ -28,8 +28,13 @@
* @author Martin Buchholz
*/
import java.util.*;
import java.util.concurrent.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
/**
* Adapted from Doug Lea, which was...
@ -71,7 +76,7 @@ public class BlockingTaskExecutor {
// are blocked. This should cause the tasks to be
// interrupted.
executor.shutdownNow();
if (! executor.awaitTermination(5, TimeUnit.SECONDS))
if (! executor.awaitTermination(5L, TimeUnit.SECONDS))
throw new Error("Executor stuck");
// Wait for the invocation thread to complete.

View File

@ -40,13 +40,21 @@
* TIMEOUT msecs to complete.
*/
import java.util.concurrent.*;
import java.util.concurrent.locks.*;
import java.util.*;
import static java.util.concurrent.TimeUnit.SECONDS;
import java.util.SplittableRandom;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.Callable;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.locks.ReentrantLock;
public final class CancelledFutureLoops {
static final ExecutorService pool = Executors.newCachedThreadPool();
static final LoopHelpers.SimpleRandom rng = new LoopHelpers.SimpleRandom();
static final SplittableRandom rnd = new SplittableRandom();
static boolean print = false;
static final int ITERS = 1000000;
static final long TIMEOUT = 100;
@ -61,7 +69,7 @@ public final class CancelledFutureLoops {
for (int i = 2; i <= maxThreads; i += (i+1) >>> 1) {
System.out.print("Threads: " + i);
try {
new FutureLoop(i).test();
new FutureLoop(i, rnd.split()).test();
}
catch (BrokenBarrierException bb) {
// OK; ignore
@ -72,19 +80,22 @@ public final class CancelledFutureLoops {
Thread.sleep(TIMEOUT);
}
pool.shutdown();
if (! pool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS))
if (! pool.awaitTermination(60L, SECONDS))
throw new Error();
}
static final class FutureLoop implements Callable {
private int v = rng.next();
private final int nthreads;
private final SplittableRandom rnd;
private final ReentrantLock lock = new ReentrantLock();
private final LoopHelpers.BarrierTimer timer = new LoopHelpers.BarrierTimer();
private final CyclicBarrier barrier;
private final int nthreads;
FutureLoop(int nthreads) {
private int v;
FutureLoop(int nthreads, SplittableRandom rnd) {
this.nthreads = nthreads;
this.rnd = rnd;
barrier = new CyclicBarrier(nthreads+1, timer);
v = rnd.nextInt();
}
final void test() throws Exception {
@ -100,7 +111,7 @@ public final class CancelledFutureLoops {
tooLate = true;
// Unbunch some of the cancels
if ( (i & 3) == 0)
Thread.sleep(1 + rng.next() % 10);
Thread.sleep(1 + rnd.nextInt(5));
}
Object f0 = futures[0].get();

View File

@ -28,9 +28,12 @@
* @author Martin Buchholz
*/
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicLong;
public class Customized {
static final AtomicLong doneCount = new AtomicLong(0);

View File

@ -38,9 +38,10 @@
* will never throw TimeoutException.
*/
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
@SuppressWarnings({"unchecked", "rawtypes", "deprecation"})
public class DoneTimedGetLoops {
@ -141,8 +142,6 @@ public class DoneTimedGetLoops {
failed++;
for (StackTraceElement e : thread.getStackTrace())
System.err.println(e);
// Kludge alert
thread.stop();
thread.join(timeoutMillis);
}
}

View File

@ -30,13 +30,12 @@
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/publicdomain/zero/1.0/
*/
import java.util.concurrent.atomic.AtomicLong;
/**
* Misc utilities in JSR166 performance tests
*/
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
class LoopHelpers {
// Some mindless computation to do between synchronizations...
@ -73,28 +72,6 @@ class LoopHelpers {
return x;
}
/**
* An actually useful random number generator, but unsynchronized.
* Basically same as java.util.Random.
*/
public static class SimpleRandom {
private static final long multiplier = 0x5DEECE66DL;
private static final long addend = 0xBL;
private static final long mask = (1L << 48) - 1;
static final AtomicLong seq = new AtomicLong(1);
private long seed = System.nanoTime() + seq.getAndIncrement();
public void setSeed(long s) {
seed = s;
}
public int next() {
long nextseed = (seed * multiplier + addend) & mask;
seed = nextseed;
return ((int)(nextseed >>> 17)) & 0x7FFFFFFF;
}
}
public static class BarrierTimer implements Runnable {
public volatile long startTime;
public volatile long endTime;

View File

@ -27,7 +27,10 @@
* @summary Check exceptional behavior in run and done methods
*/
import java.util.concurrent.*;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class Throw {

View File

@ -28,8 +28,8 @@
* @author Martin Buchholz
*/
import java.util.*;
import java.util.concurrent.*;
import java.util.Collection;
import java.util.concurrent.LinkedBlockingQueue;
public class ToArray {
public static void main(String[] args) throws Throwable {

View File

@ -37,9 +37,9 @@
* @run main FickleRegister 300
*/
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.ArrayList;
import java.util.concurrent.Phaser;
import java.util.concurrent.atomic.AtomicLong;
public class FickleRegister {
final AtomicLong count = new AtomicLong(0);

View File

@ -36,8 +36,8 @@
* @summary stress test for arrivals in a tiered phaser
* @run main TieredArriveLoops 300
*/
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.Phaser;
public class TieredArriveLoops {
final long testDurationMillisDefault = 10L * 1000L;

View File

@ -28,8 +28,12 @@
* @summary Check effectiveness of RemoveOnCancelPolicy
*/
import java.util.concurrent.*;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* Simple timer cancellation test. Submits tasks to a scheduled executor
@ -60,7 +64,7 @@ public class BasicCancelTest {
equal(tpe.getActiveCount(), 0);
equal(tpe.getPoolSize(), 0);
equal(tpe.getTaskCount(), tpe.getCompletedTaskCount());
check(tpe.awaitTermination(0, TimeUnit.SECONDS));
check(tpe.awaitTermination(0L, TimeUnit.SECONDS));
} catch (Throwable t) { unexpected(t); }
}

View File

@ -27,7 +27,13 @@
* @summary Test ScheduledThreadPoolExecutor.decorateTask
*/
import java.util.concurrent.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Delayed;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.RunnableScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
public class DecorateTask {

View File

@ -37,7 +37,10 @@
* @summary Check for long overflow in task time comparison.
*/
import java.util.concurrent.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class DelayOverflow {
static void waitForNanoTimeTick() {

View File

@ -36,8 +36,14 @@
* @summary Ensure that waiting pool threads don't retain refs to tasks.
*/
import java.lang.ref.*;
import java.util.concurrent.*;
import java.lang.ref.WeakReference;
import java.util.concurrent.Delayed;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.RunnableScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class GCRetention {
/**
@ -110,7 +116,7 @@ public class GCRetention {
Thread.sleep(10);
}
pool.shutdown();
pool.awaitTermination(10, TimeUnit.SECONDS);
pool.awaitTermination(10L, TimeUnit.SECONDS);
if (cleared < size)
throw new Error(String.format
("references to %d/%d tasks retained (\"leaked\")",

View File

@ -21,7 +21,7 @@
* questions.
*/
import java.util.concurrent.*;
import java.util.concurrent.ScheduledThreadPoolExecutor;
/**
* This is not a regression test, but a stress benchmark test for

View File

@ -37,10 +37,14 @@
* @summary Ensure relative sanity when zero core threads
*/
import java.util.concurrent.*;
import static java.util.concurrent.TimeUnit.*;
import java.util.concurrent.locks.*;
import java.lang.reflect.*;
import static java.util.concurrent.TimeUnit.HOURS;
import static java.util.concurrent.TimeUnit.SECONDS;
import java.lang.reflect.Field;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class ZeroCoreThreads {
static boolean hasWaiters(ReentrantLock lock, Condition condition) {

View File

@ -27,8 +27,10 @@
* @summary Checks that fairness setting is respected.
*/
import java.util.concurrent.*;
import java.util.concurrent.locks.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class Fairness {
private static void testFairness(boolean fair,

View File

@ -29,11 +29,19 @@
* @author Martin Buchholz
*/
import java.security.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import static java.util.concurrent.TimeUnit.*;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.MINUTES;
import static java.util.concurrent.TimeUnit.SECONDS;
import java.security.Permission;
import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;
public class ConfigChanges {
static final ThreadGroup tg = new ThreadGroup("pool");
@ -86,7 +94,7 @@ public class ConfigChanges {
equal(tpe.getActiveCount(), 0);
equal(tpe.getPoolSize(), 0);
equal(tpe.getTaskCount(), tpe.getCompletedTaskCount());
check(tpe.awaitTermination(0, SECONDS));
check(tpe.awaitTermination(0L, SECONDS));
} catch (Throwable t) { unexpected(t); }
}

View File

@ -28,7 +28,12 @@
* @author Martin Buchholz
*/
import java.util.concurrent.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class CoreThreadTimeOut {
@ -84,7 +89,7 @@ public class CoreThreadTimeOut {
equal(countExecutorThreads(), 0);
tpe.shutdown();
check(tpe.allowsCoreThreadTimeOut());
check(tpe.awaitTermination(10, TimeUnit.SECONDS));
check(tpe.awaitTermination(10L, TimeUnit.SECONDS));
System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
if (failed > 0) throw new Exception("Some tests failed");

View File

@ -28,8 +28,15 @@
* @author Martin Buchholz
*/
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.RunnableFuture;
import java.util.concurrent.RunnableScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class Custom {
static volatile int passed = 0, failed = 0;
@ -99,7 +106,7 @@ public class Custom {
equal(countExecutorThreads(), threadCount);
equal(CustomTask.births.get(), threadCount);
tpe.shutdown();
tpe.awaitTermination(120, TimeUnit.SECONDS);
tpe.awaitTermination(120L, TimeUnit.SECONDS);
Thread.sleep(1000);
equal(countExecutorThreads(), 0);
@ -109,7 +116,7 @@ public class Custom {
equal(CustomSTPE.decorations.get(), threadCount);
equal(countExecutorThreads(), threadCount);
stpe.shutdown();
stpe.awaitTermination(120, TimeUnit.SECONDS);
stpe.awaitTermination(120L, TimeUnit.SECONDS);
Thread.sleep(1000);
equal(countExecutorThreads(), 0);

View File

@ -37,7 +37,10 @@
* @summary Should be able to shutdown a pool when worker creation failed.
*/
import java.util.concurrent.*;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class FlakyThreadFactory {
void test(String[] args) throws Throwable {

View File

@ -28,7 +28,9 @@
* @author Martin Buchholz
*/
import java.util.concurrent.*;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ModifyCorePoolSize {
static void awaitPoolSize(ThreadPoolExecutor pool, int n) {

View File

@ -30,9 +30,18 @@
// based on a test kindly provided by Holger Hoffstaette <holger@wizards.de>
import java.util.concurrent.*;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Delayed;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.RunnableScheduledFuture;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class ScheduledTickleService {
// We get intermittent ClassCastException if greater than 1

View File

@ -27,7 +27,10 @@
* @summary non-idle worker threads should not be interrupted
*/
import java.util.concurrent.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class SelfInterrupt {
void test(String[] args) throws Throwable {

View File

@ -33,8 +33,10 @@
// add a call to Thread.yield() before the call to t.start()
// in ThreadPoolExecutor.addWorker.
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ShutdownNowExecuteRace {
static volatile boolean quit = false;

View File

@ -38,9 +38,12 @@
* be kept alive to service a delayed task waiting in the queue.
*/
import java.util.concurrent.*;
import static java.util.concurrent.TimeUnit.*;
import java.util.concurrent.atomic.*;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicLong;
public class ThreadRestarts {
public static void main(String[] args) throws Exception {
@ -60,7 +63,8 @@ public class ThreadRestarts {
MILLISECONDS.sleep(100L);
} finally {
stpe.shutdownNow();
stpe.awaitTermination(Long.MAX_VALUE, MILLISECONDS);
if (!stpe.awaitTermination(60L, SECONDS))
throw new AssertionError("timed out");
}
if (ctf.count.get() > 1)
throw new AssertionError(

View File

@ -28,10 +28,22 @@
* @author Martin Buchholz
*/
import java.security.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.security.Permission;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.ReentrantLock;
public class ThrowingTasks {
@ -151,7 +163,7 @@ public class ThrowingTasks {
equal(tpe.getActiveCount(), 0);
equal(tpe.getPoolSize(), 0);
equal(tpe.getTaskCount(), tpe.getCompletedTaskCount());
check(tpe.awaitTermination(0, TimeUnit.SECONDS));
check(tpe.awaitTermination(0L, TimeUnit.SECONDS));
} catch (Throwable t) { unexpected(t); }
}

View File

@ -28,8 +28,10 @@
* @author Martin Buchholz
*/
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class TimeOutShrink {
static void checkPoolSizes(ThreadPoolExecutor pool,
@ -61,7 +63,7 @@ public class TimeOutShrink {
Thread.sleep(100);
checkPoolSizes(pool, n, n, 2*n);
pool.shutdown();
pool.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
check(pool.awaitTermination(60L, TimeUnit.SECONDS));
}
//--------------------- Infrastructure ---------------------------

View File

@ -27,10 +27,22 @@
* @author Martin Buchholz
*/
import java.io.*;
import java.util.*;
import java.util.concurrent.*;
import static java.util.concurrent.TimeUnit.*;
import static java.util.concurrent.TimeUnit.DAYS;
import static java.util.concurrent.TimeUnit.HOURS;
import static java.util.concurrent.TimeUnit.MICROSECONDS;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.MINUTES;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
public class Basic {
private static void realMain(String[] args) throws Throwable {

View File

@ -31,9 +31,20 @@
* accessible fields in different locations with/without a security
* manager
*/
import java.util.concurrent.atomic.*;
import java.lang.reflect.*;
import java.security.*;
import java.lang.reflect.Field;
import java.security.AccessControlException;
import java.security.CodeSource;
import java.security.Permission;
import java.security.PermissionCollection;
import java.security.Policy;
import java.security.ProtectionDomain;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
public class AtomicUpdaters {
enum TYPE { INT, LONG, REF }
@ -76,9 +87,9 @@ public class AtomicUpdaters {
// Would like to test a public volatile in a class in another
// package - but of course there aren't any
new Config(java.util.concurrent.atomic.AtomicInteger.class, "value", "private", hasSM ? false : true, false, "private int field of class in different package", TYPE.INT),
new Config(java.util.concurrent.atomic.AtomicLong.class, "value", "private", hasSM ? false : true, false, "private long field of class in different package", TYPE.LONG),
new Config(java.util.concurrent.atomic.AtomicReference.class, "value", "private", hasSM ? false : true, false, "private reference field of class in different package", TYPE.REF),
new Config(AtomicInteger.class, "value", "private", hasSM ? false : true, false, "private int field of class in different package", TYPE.INT),
new Config(AtomicLong.class, "value", "private", hasSM ? false : true, false, "private long field of class in different package", TYPE.LONG),
new Config(AtomicReference.class, "value", "private", hasSM ? false : true, false, "private reference field of class in different package", TYPE.REF),
};
}

View File

@ -27,8 +27,16 @@
* @summary lazySet methods
*/
import java.util.concurrent.atomic.*;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerArray;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicLongArray;
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicReferenceArray;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
public class Lazy {
volatile int ii;

View File

@ -44,7 +44,6 @@ import java.io.IOException;
* Basic test to exercise the j.u.c.atomic classes that use serialization
* proxies.
*/
public class Serial {
public static void main(String[] args) {

View File

@ -36,17 +36,17 @@
* @author Doug Lea
* @bug 8004138
* @summary Check if ForkJoinPool table leaks thrown exceptions.
* @run main/othervm/timeout=1200 -Xmx32m FJExceptionTableLeak
* @run main/othervm -Xmx2200k FJExceptionTableLeak
*/
import java.util.concurrent.*;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
public class FJExceptionTableLeak {
// TODO: make this test use less time!
// Run with TASKS_PER_STEP * 40 < Xmx < STEPS * TASKS_PER_STEP * 40
// These work for Xmx32m:
static final int STEPS = 2000;
static final int TASKS_PER_STEP = 1000;
// This test was observed to fail with jdk7 -Xmx2200k,
// using STEPS = 220 and TASKS_PER_STEP = 100
static final int STEPS = 500;
static final int TASKS_PER_STEP = 100;
static class FailingTaskException extends RuntimeException {}
static class FailingTask extends RecursiveAction {

View File

@ -34,104 +34,72 @@
/*
* @test
* @bug 4486658
* @run main/timeout=7200 CheckedLockLoops
* @summary basic safety and liveness of ReentrantLocks, and other locks based on them
*/
import java.util.concurrent.*;
import java.util.concurrent.locks.*;
import java.util.*;
import static java.util.concurrent.TimeUnit.SECONDS;
import java.util.SplittableRandom;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public final class CheckedLockLoops {
static final ExecutorService pool = Executors.newCachedThreadPool();
static final LoopHelpers.SimpleRandom rng = new LoopHelpers.SimpleRandom();
static boolean print = false;
static boolean doBuiltin = false;
static ExecutorService pool;
static final SplittableRandom rnd = new SplittableRandom();
public static void main(String[] args) throws Exception {
int maxThreads = 5;
int iters = 100000;
if (args.length > 0)
maxThreads = Integer.parseInt(args[0]);
rng.setSeed(3122688L);
print = false;
System.out.println("Warmup...");
oneTest(3, 10000);
Thread.sleep(1000);
oneTest(2, 10000);
Thread.sleep(100);
oneTest(1, 100000);
Thread.sleep(100);
oneTest(1, 100000);
Thread.sleep(1000);
print = true;
final int maxThreads = (args.length > 0)
? Integer.parseInt(args[0])
: 5;
int iters = 3000;
pool = Executors.newCachedThreadPool();
for (int i = 1; i <= maxThreads; i += (i+1) >>> 1) {
System.out.println("Threads:" + i);
oneTest(i, iters / i);
Thread.sleep(100);
}
pool.shutdown();
if (! pool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS))
if (! pool.awaitTermination(10L, SECONDS))
throw new Error();
pool = null;
}
static void oneTest(int nthreads, int iters) throws Exception {
int v = rng.next();
if (doBuiltin) {
if (print)
System.out.print("builtin lock ");
new BuiltinLockLoop().test(v, nthreads, iters);
Thread.sleep(10);
}
System.out.println("Threads: " + nthreads);
int v = rnd.nextInt();
System.out.print("builtin lock ");
new BuiltinLockLoop().test(v, nthreads, iters);
if (print)
System.out.print("ReentrantLock ");
System.out.print("ReentrantLock ");
new ReentrantLockLoop().test(v, nthreads, iters);
Thread.sleep(10);
if (print)
System.out.print("Mutex ");
System.out.print("Mutex ");
new MutexLoop().test(v, nthreads, iters);
Thread.sleep(10);
if (print)
System.out.print("ReentrantWriteLock ");
System.out.print("ReentrantWriteLock ");
new ReentrantWriteLockLoop().test(v, nthreads, iters);
Thread.sleep(10);
if (print)
System.out.print("ReentrantReadWriteLock");
System.out.print("ReentrantReadWriteLock");
new ReentrantReadWriteLockLoop().test(v, nthreads, iters);
Thread.sleep(10);
if (print)
System.out.print("Semaphore ");
System.out.print("Semaphore ");
new SemaphoreLoop().test(v, nthreads, iters);
Thread.sleep(10);
if (print)
System.out.print("fair Semaphore ");
System.out.print("fair Semaphore ");
new FairSemaphoreLoop().test(v, nthreads, iters);
Thread.sleep(10);
if (print)
System.out.print("FairReentrantLock ");
System.out.print("FairReentrantLock ");
new FairReentrantLockLoop().test(v, nthreads, iters);
Thread.sleep(10);
if (print)
System.out.print("FairRWriteLock ");
System.out.print("FairRWriteLock ");
new FairReentrantWriteLockLoop().test(v, nthreads, iters);
Thread.sleep(10);
if (print)
System.out.print("FairRReadWriteLock ");
System.out.print("FairRReadWriteLock ");
new FairReentrantReadWriteLockLoop().test(v, nthreads, iters);
Thread.sleep(10);
}
abstract static class LockLoop implements Runnable {
@ -164,13 +132,11 @@ public final class CheckedLockLoops {
barrier.await();
barrier.await();
long time = timer.getTime();
if (print) {
long tpi = time / (iters * nthreads);
System.out.print("\t" + LoopHelpers.rightJustify(tpi) + " ns per update");
// double secs = (double)(time) / 1000000000.0;
// System.out.print("\t " + secs + "s run time");
System.out.println();
}
long tpi = time / (iters * nthreads);
System.out.print("\t" + LoopHelpers.rightJustify(tpi) + " ns per update");
// double secs = (double)(time) / 1000000000.0;
// System.out.print("\t " + secs + "s run time");
System.out.println();
if (result == 0) // avoid overoptimization
System.out.println("useless result: " + result);
@ -322,6 +288,7 @@ public final class CheckedLockLoops {
return sum;
}
}
private static class FairSemaphoreLoop extends LockLoop {
private final Semaphore sem = new Semaphore(1, true);
final int loop(int n) {
@ -373,7 +340,6 @@ public final class CheckedLockLoops {
}
return sum;
}
}
private static class FairReentrantReadWriteLockLoop extends LockLoop {
@ -407,6 +373,5 @@ public final class CheckedLockLoops {
}
return sum;
}
}
}

View File

@ -28,9 +28,14 @@
* @author Martin Buchholz
*/
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.locks.*;
import java.util.Random;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedLongSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
/**
* This uses a variant of the standard Mutex demo, except with a
@ -86,7 +91,7 @@ public class FlakyMutex implements Lock {
} catch (Throwable t) { unexpected(t); }}});}
barrier.await();
es.shutdown();
check(es.awaitTermination(30, TimeUnit.SECONDS));
check(es.awaitTermination(30L, TimeUnit.SECONDS));
}
private static class FlakySync extends AbstractQueuedLongSynchronizer {

View File

@ -31,13 +31,11 @@
* http://creativecommons.org/publicdomain/zero/1.0/
*/
import java.util.concurrent.atomic.AtomicLong;
/**
* Misc utilities in JSR166 performance tests
*/
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
class LoopHelpers {
// Some mindless computation to do between synchronizations...
@ -74,28 +72,6 @@ class LoopHelpers {
return x;
}
/**
* An actually useful random number generator, but unsynchronized.
* Basically same as java.util.Random.
*/
public static class SimpleRandom {
private static final long multiplier = 0x5DEECE66DL;
private static final long addend = 0xBL;
private static final long mask = (1L << 48) - 1;
static final AtomicLong seq = new AtomicLong(1);
private long seed = System.nanoTime() + seq.getAndIncrement();
public void setSeed(long s) {
seed = s;
}
public int next() {
long nextseed = (seed * multiplier + addend) & mask;
seed = nextseed;
return ((int)(nextseed >>> 17)) & 0x7FFFFFFF;
}
}
public static class BarrierTimer implements Runnable {
public volatile long startTime;
public volatile long endTime;

View File

@ -31,11 +31,13 @@
* http://creativecommons.org/publicdomain/zero/1.0/
*/
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.locks.*;
import java.util.concurrent.atomic.*;
import java.io.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.atomic.AtomicInteger;
import java.io.IOException;
import java.io.ObjectInputStream;
/**
* A sample user extension of AbstractQueuedSynchronizer.

View File

@ -26,7 +26,8 @@
* @summary Repeated timed tryAcquire shouldn't hang.
*/
import java.util.concurrent.*;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
public class TimedAcquire {
public static void main(String[] args) throws Exception {

View File

@ -40,7 +40,7 @@ import java.io.OutputStream;
import java.io.PrintStream;
import java.io.Reader;
import java.lang.ref.WeakReference;
import java.util.Random;
import java.util.SplittableRandom;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
@ -187,7 +187,7 @@ public class TimedAcquireLeak {
final String childClassName = Job.class.getName();
final String classToCheckForLeaks = Job.classToCheckForLeaks();
final String uniqueID =
String.valueOf(new Random().nextInt(Integer.MAX_VALUE));
String.valueOf(new SplittableRandom().nextInt(Integer.MAX_VALUE));
final String[] jobCmd = {
java, "-Xmx8m", "-XX:+UsePerfData",
@ -270,7 +270,7 @@ public class TimedAcquireLeak {
for (int i = 0; i < threads; i++)
new Thread() { public void run() {
try {
final Random rnd = new Random();
final SplittableRandom rnd = new SplittableRandom();
for (int j = 0; j < iterations; j++) {
if (j == iterations/10 || j == iterations - 1) {
cb.await(); // Quiesce

View File

@ -41,6 +41,7 @@
import static java.util.concurrent.TimeUnit.SECONDS;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.util.SplittableRandom;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@ -49,7 +50,7 @@ import java.util.concurrent.atomic.AtomicReferenceArray;
import java.util.concurrent.locks.LockSupport;
public final class ParkLoops {
static final int THREADS = 4; // must be power of two
static final int THREADS = 4;
// static final int ITERS = 2_000_000;
// static final int TIMEOUT = 3500; // in seconds
static final int ITERS = 100_000;
@ -64,18 +65,19 @@ public final class ParkLoops {
private final AtomicReferenceArray<Thread> threads;
private final CountDownLatch done;
private final SplittableRandom rnd;
Parker(AtomicReferenceArray<Thread> threads, CountDownLatch done) {
this.threads = threads;
this.done = done;
Parker(AtomicReferenceArray<Thread> threads,
CountDownLatch done,
SplittableRandom rnd) {
this.threads = threads; this.done = done; this.rnd = rnd;
}
public void run() {
final SimpleRandom rng = new SimpleRandom();
final Thread current = Thread.currentThread();
for (int k = ITERS, j; k > 0; k--) {
do {
j = rng.next() & (THREADS - 1);
j = rnd.nextInt(THREADS);
} while (!threads.compareAndSet(j, null, current));
do { // handle spurious wakeups
LockSupport.park();
@ -94,16 +96,17 @@ public final class ParkLoops {
private final AtomicReferenceArray<Thread> threads;
private final CountDownLatch done;
private final SplittableRandom rnd;
Unparker(AtomicReferenceArray<Thread> threads, CountDownLatch done) {
this.threads = threads;
this.done = done;
Unparker(AtomicReferenceArray<Thread> threads,
CountDownLatch done,
SplittableRandom rnd) {
this.threads = threads; this.done = done; this.rnd = rnd;
}
public void run() {
final SimpleRandom rng = new SimpleRandom();
for (int n = 0; (n++ & 0xff) != 0 || done.getCount() > 0;) {
int j = rng.next() & (THREADS - 1);
int j = rnd.nextInt(THREADS);
Thread parker = threads.get(j);
if (parker != null &&
threads.compareAndSet(j, parker, null)) {
@ -114,12 +117,13 @@ public final class ParkLoops {
}
public static void main(String[] args) throws Exception {
final SplittableRandom rnd = new SplittableRandom();
final ExecutorService pool = Executors.newCachedThreadPool();
final AtomicReferenceArray<Thread> threads
= new AtomicReferenceArray<>(THREADS);
final CountDownLatch done = new CountDownLatch(THREADS);
final Runnable parker = new Parker(threads, done);
final Runnable unparker = new Unparker(threads, done);
final Runnable parker = new Parker(threads, done, rnd.split());
final Runnable unparker = new Unparker(threads, done, rnd.split());
for (int i = 0; i < THREADS; i++) {
pool.submit(parker);
pool.submit(unparker);
@ -142,22 +146,4 @@ public final class ParkLoops {
System.err.print(threadInfo);
}
}
/**
* An actually useful random number generator, but unsynchronized.
* Basically same as java.util.Random.
*/
public static class SimpleRandom {
private static final long multiplier = 0x5DEECE66DL;
private static final long addend = 0xBL;
private static final long mask = (1L << 48) - 1;
static final AtomicLong seq = new AtomicLong(1);
private long seed = System.nanoTime() + seq.getAndIncrement();
public int next() {
long nextseed = (seed * multiplier + addend) & mask;
seed = nextseed;
return ((int)(nextseed >>> 17)) & 0x7FFFFFFF;
}
}
}

View File

@ -38,13 +38,17 @@
* @summary Checks for missed signals by locking and unlocking each of an array of locks once per thread
*/
import java.util.concurrent.*;
import java.util.concurrent.locks.*;
import java.util.*;
import static java.util.concurrent.TimeUnit.SECONDS;
import java.util.SplittableRandom;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;
public final class LockOncePerThreadLoops {
static final ExecutorService pool = Executors.newCachedThreadPool();
static final LoopHelpers.SimpleRandom rng = new LoopHelpers.SimpleRandom();
static final SplittableRandom rnd = new SplittableRandom();
static boolean print = false;
static int nlocks = 50000;
static int nthreads = 100;
@ -65,12 +69,12 @@ public final class LockOncePerThreadLoops {
Thread.sleep(100);
}
pool.shutdown();
if (! pool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS))
if (! pool.awaitTermination(60L, SECONDS))
throw new Error();
}
static final class ReentrantLockLoop implements Runnable {
private int v = rng.next();
private int v = rnd.nextInt();
private volatile int result = 17;
final ReentrantLock[]locks = new ReentrantLock[nlocks];

View File

@ -30,13 +30,12 @@
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/publicdomain/zero/1.0/
*/
import java.util.concurrent.atomic.AtomicLong;
/**
* Misc utilities in JSR166 performance tests
*/
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
class LoopHelpers {
// Some mindless computation to do between synchronizations...
@ -73,28 +72,6 @@ class LoopHelpers {
return x;
}
/**
* An actually useful random number generator, but unsynchronized.
* Basically same as java.util.Random.
*/
public static class SimpleRandom {
private static final long multiplier = 0x5DEECE66DL;
private static final long addend = 0xBL;
private static final long mask = (1L << 48) - 1;
static final AtomicLong seq = new AtomicLong(1);
private long seed = System.nanoTime() + seq.getAndIncrement();
public void setSeed(long s) {
seed = s;
}
public int next() {
long nextseed = (seed * multiplier + addend) & mask;
seed = nextseed;
return ((int)(nextseed >>> 17)) & 0x7FFFFFFF;
}
}
public static class BarrierTimer implements Runnable {
public volatile long startTime;
public volatile long endTime;

View File

@ -38,13 +38,17 @@
* @summary multiple threads using a single lock
*/
import java.util.concurrent.*;
import java.util.concurrent.locks.*;
import java.util.*;
import static java.util.concurrent.TimeUnit.SECONDS;
import java.util.SplittableRandom;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;
public final class SimpleReentrantLockLoops {
static final ExecutorService pool = Executors.newCachedThreadPool();
static final LoopHelpers.SimpleRandom rng = new LoopHelpers.SimpleRandom();
static final SplittableRandom rnd = new SplittableRandom();
static boolean print = false;
static int iters = 1000000;
@ -66,12 +70,12 @@ public final class SimpleReentrantLockLoops {
}
}
pool.shutdown();
if (! pool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS))
if (! pool.awaitTermination(60L, SECONDS))
throw new Error();
}
static final class ReentrantLockLoop implements Runnable {
private int v = rng.next();
private int v = rnd.nextInt();
private volatile int result = 17;
private final ReentrantLock lock = new ReentrantLock();
private final LoopHelpers.BarrierTimer timer = new LoopHelpers.BarrierTimer();

View File

@ -27,8 +27,9 @@
* @summary Check that regaining a read lock succeeds after a write
* lock attempt times out
*/
import java.util.concurrent.locks.*;
import java.util.concurrent.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class Bug6571733 {

View File

@ -28,10 +28,20 @@
* @author Martin Buchholz
*/
import java.io.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.locks.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Random;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
// I am the Cownt, and I lahve to cownt.
public class Count {
@ -92,7 +102,7 @@ public class Count {
barrier.await();
} catch (Throwable t) { unexpected(t); }}});}
es.shutdown();
check(es.awaitTermination(10, TimeUnit.SECONDS));
check(es.awaitTermination(10L, TimeUnit.SECONDS));
}
void testReentrantLocks(final boolean fair,

View File

@ -30,13 +30,12 @@
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/publicdomain/zero/1.0/
*/
import java.util.concurrent.atomic.AtomicLong;
/**
* Misc utilities in JSR166 performance tests
*/
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
class LoopHelpers {
// Some mindless computation to do between synchronizations...
@ -73,28 +72,6 @@ class LoopHelpers {
return x;
}
/**
* An actually useful random number generator, but unsynchronized.
* Basically same as java.util.Random.
*/
public static class SimpleRandom {
private static final long multiplier = 0x5DEECE66DL;
private static final long addend = 0xBL;
private static final long mask = (1L << 48) - 1;
static final AtomicLong seq = new AtomicLong(1);
private long seed = System.nanoTime() + seq.getAndIncrement();
public void setSeed(long s) {
seed = s;
}
public int next() {
long nextseed = (seed * multiplier + addend) & mask;
seed = nextseed;
return ((int)(nextseed >>> 17)) & 0x7FFFFFFF;
}
}
public static class BarrierTimer implements Runnable {
public volatile long startTime;
public volatile long endTime;

View File

@ -34,7 +34,6 @@
/*
* @test
* @bug 4486658
* @run main/timeout=4700 MapLoops
* @summary Exercise multithreaded maps, by default ConcurrentHashMap.
* Multithreaded hash table test. Each thread does a random walk
* though elements of "key" array. On each iteration, it checks if
@ -44,15 +43,20 @@
* parsing from command line.)
*/
import java.util.*;
import java.util.concurrent.*;
import static java.util.concurrent.TimeUnit.SECONDS;
import java.util.Map;
import java.util.SplittableRandom;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MapLoops {
static final int NKEYS = 100000;
static int pinsert = 60;
static int premove = 2;
static int maxThreads = 5;
static int nops = 1000000;
static int nops = 10000; // 1000000
static int removesPerMaxRandom;
static int insertsPerMaxRandom;
@ -89,10 +93,10 @@ public class MapLoops {
System.out.println("Using " + mapClass.getName());
Random rng = new Random(315312);
SplittableRandom rnd = new SplittableRandom();
Integer[] key = new Integer[NKEYS];
for (int i = 0; i < key.length; ++i)
key[i] = new Integer(rng.nextInt());
key[i] = new Integer(rnd.nextInt());
// warmup
System.out.println("Warmup...");
@ -100,9 +104,8 @@ public class MapLoops {
Map<Integer, Integer> map = (Map<Integer,Integer>)mapClass.newInstance();
LoopHelpers.BarrierTimer timer = new LoopHelpers.BarrierTimer();
CyclicBarrier barrier = new CyclicBarrier(1, timer);
new Runner(map, key, barrier).run();
new Runner(map, key, barrier, rnd.split()).run();
map.clear();
Thread.sleep(100);
}
for (int i = 1; i <= maxThreads; i += (i+1) >>> 1) {
@ -111,7 +114,7 @@ public class MapLoops {
LoopHelpers.BarrierTimer timer = new LoopHelpers.BarrierTimer();
CyclicBarrier barrier = new CyclicBarrier(i+1, timer);
for (int k = 0; k < i; ++k)
pool.execute(new Runner(map, key, barrier));
pool.execute(new Runner(map, key, barrier, rnd.split()));
barrier.await();
barrier.await();
long time = timer.getTime();
@ -122,28 +125,32 @@ public class MapLoops {
map.clear();
}
pool.shutdown();
if (! pool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS))
if (! pool.awaitTermination(10L, SECONDS))
throw new Error();
}
static class Runner implements Runnable {
final Map<Integer,Integer> map;
final Integer[] key;
final LoopHelpers.SimpleRandom rng = new LoopHelpers.SimpleRandom();
final CyclicBarrier barrier;
final SplittableRandom rnd;
int position;
int total;
Runner(Map<Integer,Integer> map, Integer[] key, CyclicBarrier barrier) {
Runner(Map<Integer,Integer> map,
Integer[] key,
CyclicBarrier barrier,
SplittableRandom rnd) {
this.map = map;
this.key = key;
this.barrier = barrier;
this.rnd = rnd;
position = key.length / 2;
}
int step() {
// random-walk around key positions, bunching accesses
int r = rng.next();
int r = rnd.nextInt(Integer.MAX_VALUE);
position += (r & 7) - 3;
while (position >= key.length) position -= key.length;
while (position < 0) position += key.length;

View File

@ -31,9 +31,11 @@
* http://creativecommons.org/publicdomain/zero/1.0/
*/
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.locks.*;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* This is an incomplete implementation of a wrapper class

View File

@ -38,10 +38,13 @@
* @author Chris Hegarty
*/
import static java.util.concurrent.TimeUnit.SECONDS;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import java.util.Iterator;
import java.util.concurrent.Phaser;
import java.util.concurrent.TimeUnit;
import static java.util.concurrent.TimeUnit.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
@ -287,12 +290,34 @@ public class Basic {
public void remove() {throw new UnsupportedOperationException();}};
}
private static void realMain(String[] args) throws Throwable {
static class SimpleTimer {
long startTime = System.nanoTime();
long elapsedMillis() {
long now = System.nanoTime();
long elapsed = NANOSECONDS.toMillis(now - startTime);
startTime = now;
return elapsed;
}
void printElapsed() { System.out.println(elapsedMillis() + " ms"); }
}
Thread.currentThread().setName("mainThread");
static void waitForThreadToBlock(Thread thread) {
for (long startTime = 0;;) {
Thread.State state = thread.getState();
if (state == Thread.State.WAITING ||
state == Thread.State.TIMED_WAITING)
break;
if (startTime == 0) startTime = System.nanoTime();
else if (System.nanoTime() - startTime > 10L * 1000L * 1000L * 1000L)
throw new AssertionError("timed out waiting for thread to block");
}
}
private static void realMain(String[] args) throws Throwable {
SimpleTimer timer = new SimpleTimer();
//----------------------------------------------------------------
// Some basic sanity
System.out.print("Some basic sanity: ");
//----------------------------------------------------------------
try {
final StampedLock sl = new StampedLock();
@ -309,10 +334,10 @@ public class Basic {
check(!sl.isReadLocked());
check(sl.isWriteLocked());
check(sl.tryReadLock() == 0L);
check(sl.tryReadLock(100, MILLISECONDS) == 0L);
check(sl.tryReadLock(1, MILLISECONDS) == 0L);
check(sl.tryOptimisticRead() == 0L);
check(sl.tryWriteLock() == 0L);
check(sl.tryWriteLock(100, MILLISECONDS) == 0L);
check(sl.tryWriteLock(1, MILLISECONDS) == 0L);
check(!sl.tryUnlockRead());
check(sl.tryConvertToWriteLock(stamp) == stamp);
try {
@ -334,7 +359,7 @@ public class Basic {
check(!sl.isWriteLocked());
check(sl.tryOptimisticRead() != 0L);
check(sl.tryWriteLock() == 0L);
check(sl.tryWriteLock(100, MILLISECONDS) == 0L);
check(sl.tryWriteLock(1, MILLISECONDS) == 0L);
check(!sl.tryUnlockWrite());
check(sl.tryConvertToReadLock(stamp) == stamp);
try {
@ -349,105 +374,136 @@ public class Basic {
}
check(!sl.isReadLocked());
stamp = sl.tryReadLock(100, MILLISECONDS);
stamp = sl.tryReadLock(1, MILLISECONDS);
try {
check(stamp != 0L);
} finally {
sl.unlockRead(stamp);
}
} catch (Throwable t) { unexpected(t); }
timer.printElapsed();
//----------------------------------------------------------------
// Multiple writers single reader
System.out.print("Multiple writers single reader: ");
//----------------------------------------------------------------
try {
StampedLock sl = new StampedLock();
Phaser gate = new Phaser(102);
int nThreads = 10;
Phaser gate = new Phaser(nThreads + 2);
Iterator<Writer> writers = writerIterator(sl, gate);
Iterator<Reader> readers = readerIterator(sl, gate);
for (int i = 0; i < 10; i++) {
for (int i = 0; i < 2; i++) {
check(!sl.isReadLocked());
check(!sl.isWriteLocked());
check(!sl.tryUnlockRead());
check(!sl.tryUnlockWrite());
check(sl.tryOptimisticRead() != 0L);
Locker[] wThreads = new Locker[100];
for (int j=0; j<100; j++)
Locker[] wThreads = new Locker[nThreads];
for (int j=0; j<nThreads; j++)
wThreads[j] = writers.next();
for (int j=0; j<100; j++)
for (int j=0; j<nThreads; j++)
wThreads[j].start();
Reader reader = readers.next(); reader.start();
toTheStartingGate(gate);
reader.join();
for (int j=0; j<100; j++)
for (int j=0; j<nThreads; j++)
wThreads[j].join();
for (int j=0; j<100; j++)
for (int j=0; j<nThreads; j++)
checkResult(wThreads[j], null);
checkResult(reader, null);
}
} catch (Throwable t) { unexpected(t); }
timer.printElapsed();
//----------------------------------------------------------------
// Multiple readers single writer
System.out.print("Multiple readers single writer: ");
//----------------------------------------------------------------
try {
StampedLock sl = new StampedLock();
Phaser gate = new Phaser(102);
int nThreads = 10;
Phaser gate = new Phaser(nThreads + 2);
Iterator<Writer> writers = writerIterator(sl, gate);
Iterator<Reader> readers = readerIterator(sl, gate);
for (int i = 0; i < 10; i++) {
for (int i = 0; i < 2; i++) {
check(!sl.isReadLocked());
check(!sl.isWriteLocked());
check(!sl.tryUnlockRead());
check(!sl.tryUnlockWrite());
check(sl.tryOptimisticRead() != 0L);
Locker[] rThreads = new Locker[100];
for (int j=0; j<100; j++)
Locker[] rThreads = new Locker[nThreads];
for (int j=0; j<nThreads; j++)
rThreads[j] = readers.next();
for (int j=0; j<100; j++)
for (int j=0; j<nThreads; j++)
rThreads[j].start();
Writer writer = writers.next(); writer.start();
toTheStartingGate(gate);
writer.join();
for (int j=0; j<100; j++)
for (int j=0; j<nThreads; j++)
rThreads[j].join();
for (int j=0; j<100; j++)
for (int j=0; j<nThreads; j++)
checkResult(rThreads[j], null);
checkResult(writer, null);
}
} catch (Throwable t) { unexpected(t); }
timer.printElapsed();
//----------------------------------------------------------------
// thread interrupted
System.out.print("thread interrupted: ");
//----------------------------------------------------------------
try {
// We test interrupting both before and after trying to acquire
boolean view = false;
StampedLock sl = new StampedLock();
for (long timeout : new long[] { -1L, 30L, -1L, 30L }) {
long stamp = sl.writeLock();
long stamp;
Thread.State state;
stamp = sl.writeLock();
try {
Reader r = interruptibleReader(sl, timeout, SECONDS, null, view);
r.start();
// allow r to block
Thread.sleep(2000);
r.interrupt();
r.join();
checkResult(r, InterruptedException.class);
} finally {
sl.unlockWrite(stamp);
}
stamp = sl.writeLock();
try {
Reader r = interruptibleReader(sl, timeout, SECONDS, null, view);
r.start();
waitForThreadToBlock(r);
r.interrupt();
r.join();
checkResult(r, InterruptedException.class);
} finally {
sl.unlockWrite(stamp);
}
stamp = sl.readLock();
try {
Writer w = interruptibleWriter(sl, timeout, SECONDS, null, view);
w.start();
// allow w to block
Thread.sleep(2000);
w.interrupt();
w.join();
checkResult(w, InterruptedException.class);
} finally {
sl.unlockRead(stamp);
}
stamp = sl.readLock();
try {
Writer w = interruptibleWriter(sl, timeout, SECONDS, null, view);
w.start();
waitForThreadToBlock(w);
w.interrupt();
w.join();
checkResult(w, InterruptedException.class);
} finally {
sl.unlockRead(stamp);
}
check(!sl.isReadLocked());
check(!sl.isWriteLocked());
check(!sl.tryUnlockRead());
@ -457,22 +513,23 @@ public class Basic {
view = true;
}
} catch (Throwable t) { unexpected(t); }
timer.printElapsed();
//----------------------------------------------------------------
// timeout
System.out.print("timeout: ");
//----------------------------------------------------------------
try {
StampedLock sl = new StampedLock();
for (long timeout : new long[] { 0L, 5L }) {
long stamp = sl.writeLock();
try {
check(sl.tryReadLock(timeout, SECONDS) == 0L);
check(sl.tryReadLock(timeout, MILLISECONDS) == 0L);
} finally {
sl.unlockWrite(stamp);
}
stamp = sl.readLock();
try {
check(sl.tryWriteLock(timeout, SECONDS) == 0L);
check(sl.tryWriteLock(timeout, MILLISECONDS) == 0L);
} finally {
sl.unlockRead(stamp);
}
@ -483,9 +540,10 @@ public class Basic {
check(sl.tryOptimisticRead() != 0L);
}
} catch (Throwable t) { unexpected(t); }
timer.printElapsed();
//----------------------------------------------------------------
// optimistic read
System.out.print("optimistic read: ");
//----------------------------------------------------------------
try {
StampedLock sl = new StampedLock();
@ -510,9 +568,10 @@ public class Basic {
check(sl.validate(stamp) == false);
}
} catch (Throwable t) { unexpected(t); }
timer.printElapsed();
//----------------------------------------------------------------
// convert
System.out.print("convert: ");
//----------------------------------------------------------------
try {
StampedLock sl = new StampedLock();
@ -527,12 +586,12 @@ public class Basic {
check(sl.validate(stamp));
check(sl.isReadLocked());
check(sl.tryWriteLock() == 0L);
check(sl.tryWriteLock(1L, SECONDS) == 0L);
check(sl.tryWriteLock(1L, MILLISECONDS) == 0L);
check((stamp = sl.tryConvertToWriteLock(stamp)) != 0L);
check(sl.validate(stamp));
check(!sl.isReadLocked());
check(sl.isWriteLocked());
check(sl.tryReadLock(1L, SECONDS) == 0L);
check(sl.tryReadLock(1L, MILLISECONDS) == 0L);
if (i != 0) {
sl.unlockWrite(stamp);
continue;
@ -543,7 +602,7 @@ public class Basic {
check(sl.isReadLocked());
check(!sl.isWriteLocked());
check(sl.tryWriteLock() == 0L);
check(sl.tryWriteLock(1L, SECONDS) == 0L);
check(sl.tryWriteLock(1L, MILLISECONDS) == 0L);
check((stamp = sl.tryConvertToOptimisticRead(stamp)) != 0L);
check(sl.validate(stamp));
check(!sl.isReadLocked());
@ -551,9 +610,10 @@ public class Basic {
check(sl.validate(stamp));
}
} catch (Throwable t) { unexpected(t); }
timer.printElapsed();
//----------------------------------------------------------------
// views
System.out.print("views: ");
//----------------------------------------------------------------
try {
StampedLock sl = new StampedLock();
@ -566,7 +626,7 @@ public class Basic {
check(sl.isReadLocked());
check(!sl.isWriteLocked());
check(sl.tryWriteLock() == 0L);
check(sl.tryWriteLock(1L, SECONDS) == 0L);
check(sl.tryWriteLock(1L, MILLISECONDS) == 0L);
} finally {
rl.unlock();
}
@ -578,7 +638,7 @@ public class Basic {
check(!sl.isReadLocked());
check(sl.isWriteLocked());
check(sl.tryWriteLock() == 0L);
check(sl.tryWriteLock(1L, SECONDS) == 0L);
check(sl.tryWriteLock(1L, MILLISECONDS) == 0L);
} finally {
wl.unlock();
}
@ -590,6 +650,7 @@ public class Basic {
wl = rwl.writeLock();
}
} catch (Throwable t) { unexpected(t); }
timer.printElapsed();
}
//--------------------- Infrastructure ---------------------------