undefect. CWE-407 — 63 sites patched across 27 ecosystems
Authors: russell@unturf.com · brackishbert@gmail.com · foxhop.net · TimeHexOn.com Patches, unit tests, benchmarks, whitepaper, and outreach briefs. Public domain — no copyright claimed. Use freely.
This commit is contained in:
commit
0a580b313d
70422 changed files with 17213626 additions and 0 deletions
379
test/jdk/java/util/concurrent/locks/Lock/CheckedLockLoops.java
Normal file
379
test/jdk/java/util/concurrent/locks/Lock/CheckedLockLoops.java
Normal file
|
|
@ -0,0 +1,379 @@
|
|||
/*
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
/*
|
||||
* This file is available under and governed by the GNU General Public
|
||||
* License version 2 only, as published by the Free Software Foundation.
|
||||
* However, the following notice accompanied the original version of this
|
||||
* file:
|
||||
*
|
||||
* Written by Doug Lea with assistance from members of JCP JSR-166
|
||||
* Expert Group and released to the public domain, as explained at
|
||||
* http://creativecommons.org/publicdomain/zero/1.0/
|
||||
*/
|
||||
|
||||
/*
|
||||
* @test
|
||||
* @bug 4486658
|
||||
* @summary basic safety and liveness of ReentrantLocks, and other locks based on them
|
||||
* @library /test/lib
|
||||
*/
|
||||
|
||||
import static java.util.concurrent.TimeUnit.MILLISECONDS;
|
||||
|
||||
import java.util.concurrent.CyclicBarrier;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Semaphore;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.concurrent.locks.Lock;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
import java.util.concurrent.locks.ReentrantReadWriteLock;
|
||||
import jdk.test.lib.Utils;
|
||||
|
||||
public final class CheckedLockLoops {
|
||||
static final long LONG_DELAY_MS = Utils.adjustTimeout(10_000);
|
||||
static ExecutorService pool;
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
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) {
|
||||
oneTest(i, iters / i);
|
||||
}
|
||||
pool.shutdown();
|
||||
if (! pool.awaitTermination(LONG_DELAY_MS, MILLISECONDS))
|
||||
throw new Error();
|
||||
pool = null;
|
||||
}
|
||||
|
||||
static void oneTest(int nthreads, int iters) throws Exception {
|
||||
System.out.println("Threads: " + nthreads);
|
||||
int v = ThreadLocalRandom.current().nextInt();
|
||||
System.out.print("builtin lock ");
|
||||
new BuiltinLockLoop().test(v, nthreads, iters);
|
||||
|
||||
System.out.print("ReentrantLock ");
|
||||
new ReentrantLockLoop().test(v, nthreads, iters);
|
||||
|
||||
System.out.print("Mutex ");
|
||||
new MutexLoop().test(v, nthreads, iters);
|
||||
|
||||
System.out.print("ReentrantWriteLock ");
|
||||
new ReentrantWriteLockLoop().test(v, nthreads, iters);
|
||||
|
||||
System.out.print("ReentrantReadWriteLock");
|
||||
new ReentrantReadWriteLockLoop().test(v, nthreads, iters);
|
||||
|
||||
System.out.print("Semaphore ");
|
||||
new SemaphoreLoop().test(v, nthreads, iters);
|
||||
|
||||
System.out.print("fair Semaphore ");
|
||||
new FairSemaphoreLoop().test(v, nthreads, iters);
|
||||
|
||||
System.out.print("FairReentrantLock ");
|
||||
new FairReentrantLockLoop().test(v, nthreads, iters);
|
||||
|
||||
System.out.print("FairRWriteLock ");
|
||||
new FairReentrantWriteLockLoop().test(v, nthreads, iters);
|
||||
|
||||
System.out.print("FairRReadWriteLock ");
|
||||
new FairReentrantReadWriteLockLoop().test(v, nthreads, iters);
|
||||
}
|
||||
|
||||
abstract static class LockLoop implements Runnable {
|
||||
int value;
|
||||
int checkValue;
|
||||
int iters;
|
||||
volatile int result;
|
||||
final LoopHelpers.BarrierTimer timer = new LoopHelpers.BarrierTimer();
|
||||
CyclicBarrier barrier;
|
||||
|
||||
final int setValue(int v) {
|
||||
checkValue = v ^ 0x55555555;
|
||||
value = v;
|
||||
return v;
|
||||
}
|
||||
|
||||
final int getValue() {
|
||||
int v = value;
|
||||
if (checkValue != ~(v ^ 0xAAAAAAAA))
|
||||
throw new Error("lock protection failure");
|
||||
return v;
|
||||
}
|
||||
|
||||
final void test(int initialValue, int nthreads, int iters) throws Exception {
|
||||
setValue(initialValue);
|
||||
this.iters = iters;
|
||||
barrier = new CyclicBarrier(nthreads+1, timer);
|
||||
for (int i = 0; i < nthreads; ++i)
|
||||
pool.execute(this);
|
||||
barrier.await();
|
||||
barrier.await();
|
||||
long time = timer.getTime();
|
||||
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);
|
||||
}
|
||||
abstract int loop(int n);
|
||||
public final void run() {
|
||||
try {
|
||||
barrier.await();
|
||||
result += loop(iters);
|
||||
barrier.await();
|
||||
}
|
||||
catch (Exception ex) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static class BuiltinLockLoop extends LockLoop {
|
||||
final int loop(int n) {
|
||||
int sum = 0;
|
||||
int x = 0;
|
||||
while (n-- > 0) {
|
||||
synchronized (this) {
|
||||
x = setValue(LoopHelpers.compute1(getValue()));
|
||||
}
|
||||
sum += LoopHelpers.compute2(x);
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
}
|
||||
|
||||
private static class ReentrantLockLoop extends LockLoop {
|
||||
private final ReentrantLock lock = new ReentrantLock();
|
||||
final int loop(int n) {
|
||||
final ReentrantLock lock = this.lock;
|
||||
int sum = 0;
|
||||
int x = 0;
|
||||
while (n-- > 0) {
|
||||
lock.lock();
|
||||
try {
|
||||
x = setValue(LoopHelpers.compute1(getValue()));
|
||||
}
|
||||
finally {
|
||||
lock.unlock();
|
||||
}
|
||||
sum += LoopHelpers.compute2(x);
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
}
|
||||
|
||||
private static class MutexLoop extends LockLoop {
|
||||
private final Mutex lock = new Mutex();
|
||||
final int loop(int n) {
|
||||
final Mutex lock = this.lock;
|
||||
int sum = 0;
|
||||
int x = 0;
|
||||
while (n-- > 0) {
|
||||
lock.lock();
|
||||
try {
|
||||
x = setValue(LoopHelpers.compute1(getValue()));
|
||||
}
|
||||
finally {
|
||||
lock.unlock();
|
||||
}
|
||||
sum += LoopHelpers.compute2(x);
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
}
|
||||
|
||||
private static class FairReentrantLockLoop extends LockLoop {
|
||||
private final ReentrantLock lock = new ReentrantLock(true);
|
||||
final int loop(int n) {
|
||||
final ReentrantLock lock = this.lock;
|
||||
int sum = 0;
|
||||
int x = 0;
|
||||
while (n-- > 0) {
|
||||
lock.lock();
|
||||
try {
|
||||
x = setValue(LoopHelpers.compute1(getValue()));
|
||||
}
|
||||
finally {
|
||||
lock.unlock();
|
||||
}
|
||||
sum += LoopHelpers.compute2(x);
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
}
|
||||
|
||||
private static class ReentrantWriteLockLoop extends LockLoop {
|
||||
private final Lock lock = new ReentrantReadWriteLock().writeLock();
|
||||
final int loop(int n) {
|
||||
final Lock lock = this.lock;
|
||||
int sum = 0;
|
||||
int x = 0;
|
||||
while (n-- > 0) {
|
||||
lock.lock();
|
||||
try {
|
||||
x = setValue(LoopHelpers.compute1(getValue()));
|
||||
}
|
||||
finally {
|
||||
lock.unlock();
|
||||
}
|
||||
sum += LoopHelpers.compute2(x);
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
}
|
||||
|
||||
private static class FairReentrantWriteLockLoop extends LockLoop {
|
||||
final Lock lock = new ReentrantReadWriteLock(true).writeLock();
|
||||
final int loop(int n) {
|
||||
final Lock lock = this.lock;
|
||||
int sum = 0;
|
||||
int x = 0;
|
||||
while (n-- > 0) {
|
||||
lock.lock();
|
||||
try {
|
||||
x = setValue(LoopHelpers.compute1(getValue()));
|
||||
}
|
||||
finally {
|
||||
lock.unlock();
|
||||
}
|
||||
sum += LoopHelpers.compute2(x);
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
}
|
||||
|
||||
private static class SemaphoreLoop extends LockLoop {
|
||||
private final Semaphore sem = new Semaphore(1, false);
|
||||
final int loop(int n) {
|
||||
final Semaphore sem = this.sem;
|
||||
int sum = 0;
|
||||
int x = 0;
|
||||
while (n-- > 0) {
|
||||
sem.acquireUninterruptibly();
|
||||
try {
|
||||
x = setValue(LoopHelpers.compute1(getValue()));
|
||||
}
|
||||
finally {
|
||||
sem.release();
|
||||
}
|
||||
sum += LoopHelpers.compute2(x);
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
}
|
||||
|
||||
private static class FairSemaphoreLoop extends LockLoop {
|
||||
private final Semaphore sem = new Semaphore(1, true);
|
||||
final int loop(int n) {
|
||||
final Semaphore sem = this.sem;
|
||||
int sum = 0;
|
||||
int x = 0;
|
||||
while (n-- > 0) {
|
||||
sem.acquireUninterruptibly();
|
||||
try {
|
||||
x = setValue(LoopHelpers.compute1(getValue()));
|
||||
}
|
||||
finally {
|
||||
sem.release();
|
||||
}
|
||||
sum += LoopHelpers.compute2(x);
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
}
|
||||
|
||||
private static class ReentrantReadWriteLockLoop extends LockLoop {
|
||||
private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
|
||||
final int loop(int n) {
|
||||
final Lock rlock = lock.readLock();
|
||||
final Lock wlock = lock.writeLock();
|
||||
int sum = 0;
|
||||
int x = 0;
|
||||
while (n-- > 0) {
|
||||
if ((n & 16) != 0) {
|
||||
rlock.lock();
|
||||
try {
|
||||
x = LoopHelpers.compute1(getValue());
|
||||
x = LoopHelpers.compute2(x);
|
||||
}
|
||||
finally {
|
||||
rlock.unlock();
|
||||
}
|
||||
}
|
||||
else {
|
||||
wlock.lock();
|
||||
try {
|
||||
setValue(x);
|
||||
}
|
||||
finally {
|
||||
wlock.unlock();
|
||||
}
|
||||
sum += LoopHelpers.compute2(x);
|
||||
}
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
}
|
||||
|
||||
private static class FairReentrantReadWriteLockLoop extends LockLoop {
|
||||
private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true);
|
||||
final int loop(int n) {
|
||||
final Lock rlock = lock.readLock();
|
||||
final Lock wlock = lock.writeLock();
|
||||
int sum = 0;
|
||||
int x = 0;
|
||||
while (n-- > 0) {
|
||||
if ((n & 16) != 0) {
|
||||
rlock.lock();
|
||||
try {
|
||||
x = LoopHelpers.compute1(getValue());
|
||||
x = LoopHelpers.compute2(x);
|
||||
}
|
||||
finally {
|
||||
rlock.unlock();
|
||||
}
|
||||
}
|
||||
else {
|
||||
wlock.lock();
|
||||
try {
|
||||
setValue(x);
|
||||
}
|
||||
finally {
|
||||
wlock.unlock();
|
||||
}
|
||||
sum += LoopHelpers.compute2(x);
|
||||
}
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
}
|
||||
}
|
||||
180
test/jdk/java/util/concurrent/locks/Lock/FlakyMutex.java
Normal file
180
test/jdk/java/util/concurrent/locks/Lock/FlakyMutex.java
Normal file
|
|
@ -0,0 +1,180 @@
|
|||
/*
|
||||
* Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
/*
|
||||
* @test
|
||||
* @bug 6503247 6574123
|
||||
* @summary Test resilience to tryAcquire methods that throw
|
||||
* @author Martin Buchholz
|
||||
*/
|
||||
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
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
|
||||
* tryAcquire method that randomly throws various Throwable
|
||||
* subclasses.
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public class FlakyMutex implements Lock {
|
||||
static class MyError extends Error {}
|
||||
static class MyException extends Exception {}
|
||||
static class MyRuntimeException extends RuntimeException {}
|
||||
|
||||
static void checkThrowable(Throwable t) {
|
||||
if (!((t instanceof MyError) ||
|
||||
(t instanceof MyException) ||
|
||||
(t instanceof MyRuntimeException)))
|
||||
unexpected(t);
|
||||
}
|
||||
|
||||
static void realMain(String[] args) throws Throwable {
|
||||
final ThreadLocalRandom rndMain = ThreadLocalRandom.current();
|
||||
final int nCpus = Runtime.getRuntime().availableProcessors();
|
||||
final int maxThreads = Math.min(4, nCpus);
|
||||
final int nThreads = rndMain.nextInt(1, maxThreads + 1);
|
||||
final int iterations = 10_000;
|
||||
final CyclicBarrier startingGate = new CyclicBarrier(nThreads);
|
||||
final ExecutorService es = Executors.newFixedThreadPool(nThreads);
|
||||
final FlakyMutex mutex = new FlakyMutex();
|
||||
final Runnable task = () -> {
|
||||
try {
|
||||
ThreadLocalRandom rnd = ThreadLocalRandom.current();
|
||||
startingGate.await();
|
||||
for (int i = 0; i < iterations; i++) {
|
||||
for (;;) {
|
||||
try {
|
||||
if (rnd.nextBoolean())
|
||||
mutex.lock();
|
||||
else
|
||||
mutex.lockInterruptibly();
|
||||
break;
|
||||
} catch (Throwable t) { checkThrowable(t); }
|
||||
}
|
||||
|
||||
if (rnd.nextBoolean()) {
|
||||
try {
|
||||
check(! mutex.tryLock());
|
||||
} catch (Throwable t) { checkThrowable(t); }
|
||||
}
|
||||
|
||||
if (rnd.nextInt(10) == 0) {
|
||||
try {
|
||||
check(! mutex.tryLock(1, TimeUnit.MICROSECONDS));
|
||||
} catch (Throwable t) { checkThrowable(t); }
|
||||
}
|
||||
|
||||
if (rnd.nextBoolean()) {
|
||||
check(mutex.isLocked());
|
||||
}
|
||||
|
||||
mutex.unlock();
|
||||
}
|
||||
} catch (Throwable t) { unexpected(t); }
|
||||
};
|
||||
|
||||
for (int i = 0; i < nThreads; i++)
|
||||
es.submit(task);
|
||||
es.shutdown();
|
||||
// Let test harness handle timeout
|
||||
check(es.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS));
|
||||
}
|
||||
|
||||
private static class FlakySync extends AbstractQueuedLongSynchronizer {
|
||||
private static final long serialVersionUID = -1L;
|
||||
|
||||
public boolean isHeldExclusively() { return getState() == 1; }
|
||||
|
||||
public boolean tryAcquire(long acquires) {
|
||||
// Sneak in some tests for queue state
|
||||
if (hasQueuedPredecessors())
|
||||
check(getFirstQueuedThread() != Thread.currentThread());
|
||||
if (getFirstQueuedThread() == Thread.currentThread()) {
|
||||
check(hasQueuedThreads());
|
||||
check(!hasQueuedPredecessors());
|
||||
} else {
|
||||
// Might be true, but only transiently
|
||||
do {} while (hasQueuedPredecessors() != hasQueuedThreads());
|
||||
}
|
||||
|
||||
switch (ThreadLocalRandom.current().nextInt(10)) {
|
||||
case 0: throw new MyError();
|
||||
case 1: throw new MyRuntimeException();
|
||||
case 2: FlakyMutex.<RuntimeException>uncheckedThrow(new MyException());
|
||||
// fall through ... NOT!
|
||||
default: return compareAndSetState(0, 1);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean tryRelease(long releases) {
|
||||
setState(0);
|
||||
return true;
|
||||
}
|
||||
|
||||
Condition newCondition() { return new ConditionObject(); }
|
||||
}
|
||||
|
||||
private final FlakySync sync = new FlakySync();
|
||||
public void lock() { sync.acquire(1); }
|
||||
public boolean tryLock() { return sync.tryAcquire(1); }
|
||||
public void lockInterruptibly() throws InterruptedException {
|
||||
sync.acquireInterruptibly(1);
|
||||
}
|
||||
public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException {
|
||||
return sync.tryAcquireNanos(1, unit.toNanos(timeout));
|
||||
}
|
||||
public void unlock() { sync.release(1); }
|
||||
public Condition newCondition() { return sync.newCondition(); }
|
||||
public boolean isLocked() { return sync.isHeldExclusively(); }
|
||||
public boolean hasQueuedThreads() { return sync.hasQueuedThreads(); }
|
||||
|
||||
//--------------------- Infrastructure ---------------------------
|
||||
static volatile int passed = 0, failed = 0;
|
||||
static void pass() {passed++;}
|
||||
static void fail() {failed++; Thread.dumpStack();}
|
||||
static void fail(String msg) {System.out.println(msg); fail();}
|
||||
static void unexpected(Throwable t) {failed++; t.printStackTrace();}
|
||||
static void check(boolean cond) {if (cond) pass(); else fail();}
|
||||
static void equal(Object x, Object y) {
|
||||
if (x == null ? y == null : x.equals(y)) pass();
|
||||
else fail(x + " not equal to " + y);}
|
||||
public static void main(String[] args) throws Throwable {
|
||||
int runsPerTest = Integer.getInteger("jsr166.runsPerTest", 1);
|
||||
try {
|
||||
for (int i = runsPerTest; i--> 0; )
|
||||
realMain(args);
|
||||
} catch (Throwable t) { unexpected(t); }
|
||||
System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
|
||||
if (failed > 0) throw new AssertionError("Some tests failed");}
|
||||
@SuppressWarnings("unchecked")
|
||||
static <T extends Throwable> void uncheckedThrow(Throwable t) throws T {
|
||||
throw (T)t; // rely on vacuous cast
|
||||
}
|
||||
}
|
||||
103
test/jdk/java/util/concurrent/locks/Lock/LoopHelpers.java
Normal file
103
test/jdk/java/util/concurrent/locks/Lock/LoopHelpers.java
Normal file
|
|
@ -0,0 +1,103 @@
|
|||
/*
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
/*
|
||||
* This file is available under and governed by the GNU General Public
|
||||
* License version 2 only, as published by the Free Software Foundation.
|
||||
* However, the following notice accompanied the original version of this
|
||||
* file:
|
||||
*
|
||||
* Written by Doug Lea with assistance from members of JCP JSR-166
|
||||
* Expert Group and released to the public domain, as explained at
|
||||
* http://creativecommons.org/publicdomain/zero/1.0/
|
||||
*/
|
||||
|
||||
/**
|
||||
* Misc utilities in JSR166 performance tests
|
||||
*/
|
||||
class LoopHelpers {
|
||||
|
||||
// Some mindless computation to do between synchronizations...
|
||||
|
||||
/**
|
||||
* generates 32 bit pseudo-random numbers.
|
||||
* Adapted from http://www.snippets.org
|
||||
*/
|
||||
public static int compute1(int x) {
|
||||
int lo = 16807 * (x & 0xFFFF);
|
||||
int hi = 16807 * (x >>> 16);
|
||||
lo += (hi & 0x7FFF) << 16;
|
||||
if ((lo & 0x80000000) != 0) {
|
||||
lo &= 0x7fffffff;
|
||||
++lo;
|
||||
}
|
||||
lo += hi >>> 15;
|
||||
if (lo == 0 || (lo & 0x80000000) != 0) {
|
||||
lo &= 0x7fffffff;
|
||||
++lo;
|
||||
}
|
||||
return lo;
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes a linear congruential random number a random number
|
||||
* of times.
|
||||
*/
|
||||
public static int compute2(int x) {
|
||||
int loops = (x >>> 4) & 7;
|
||||
while (loops-- > 0) {
|
||||
x = (x * 2147483647) % 16807;
|
||||
}
|
||||
return x;
|
||||
}
|
||||
|
||||
public static class BarrierTimer implements Runnable {
|
||||
public volatile long startTime;
|
||||
public volatile long endTime;
|
||||
public void run() {
|
||||
long t = System.nanoTime();
|
||||
if (startTime == 0)
|
||||
startTime = t;
|
||||
else
|
||||
endTime = t;
|
||||
}
|
||||
public void clear() {
|
||||
startTime = 0;
|
||||
endTime = 0;
|
||||
}
|
||||
public long getTime() {
|
||||
return endTime - startTime;
|
||||
}
|
||||
}
|
||||
|
||||
public static String rightJustify(long n) {
|
||||
// There's probably a better way to do this...
|
||||
String field = " ";
|
||||
String num = Long.toString(n);
|
||||
if (num.length() >= field.length())
|
||||
return num;
|
||||
StringBuilder b = new StringBuilder(field);
|
||||
b.replace(b.length()-num.length(), b.length(), num);
|
||||
return b.toString();
|
||||
}
|
||||
|
||||
}
|
||||
83
test/jdk/java/util/concurrent/locks/Lock/Mutex.java
Normal file
83
test/jdk/java/util/concurrent/locks/Lock/Mutex.java
Normal file
|
|
@ -0,0 +1,83 @@
|
|||
/*
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
/*
|
||||
* This file is available under and governed by the GNU General Public
|
||||
* License version 2 only, as published by the Free Software Foundation.
|
||||
* However, the following notice accompanied the original version of this
|
||||
* file:
|
||||
*
|
||||
* Written by Doug Lea with assistance from members of JCP JSR-166
|
||||
* Expert Group and released to the public domain, as explained at
|
||||
* http://creativecommons.org/publicdomain/zero/1.0/
|
||||
*/
|
||||
|
||||
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.io.IOException;
|
||||
import java.io.ObjectInputStream;
|
||||
|
||||
/**
|
||||
* A sample user extension of AbstractQueuedSynchronizer.
|
||||
*/
|
||||
public class Mutex implements Lock, java.io.Serializable {
|
||||
private static class Sync extends AbstractQueuedSynchronizer {
|
||||
public boolean isHeldExclusively() { return getState() == 1; }
|
||||
|
||||
public boolean tryAcquire(int acquires) {
|
||||
assert acquires == 1; // Does not use multiple acquires
|
||||
return compareAndSetState(0, 1);
|
||||
}
|
||||
|
||||
public boolean tryRelease(int releases) {
|
||||
setState(0);
|
||||
return true;
|
||||
}
|
||||
|
||||
Condition newCondition() { return new ConditionObject(); }
|
||||
|
||||
private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException {
|
||||
s.defaultReadObject();
|
||||
setState(0); // reset to unlocked state
|
||||
}
|
||||
}
|
||||
|
||||
private final Sync sync = new Sync();
|
||||
public void lock() {
|
||||
sync.acquire(1);
|
||||
}
|
||||
public boolean tryLock() {
|
||||
return sync.tryAcquire(1);
|
||||
}
|
||||
public void lockInterruptibly() throws InterruptedException {
|
||||
sync.acquireInterruptibly(1);
|
||||
}
|
||||
public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException {
|
||||
return sync.tryAcquireNanos(1, unit.toNanos(timeout));
|
||||
}
|
||||
public void unlock() { sync.release(1); }
|
||||
public Condition newCondition() { return sync.newCondition(); }
|
||||
public boolean isLocked() { return sync.isHeldExclusively(); }
|
||||
public boolean hasQueuedThreads() { return sync.hasQueuedThreads(); }
|
||||
}
|
||||
145
test/jdk/java/util/concurrent/locks/Lock/OOMEInAQS.java
Normal file
145
test/jdk/java/util/concurrent/locks/Lock/OOMEInAQS.java
Normal file
|
|
@ -0,0 +1,145 @@
|
|||
/*
|
||||
* Copyright (c) 2013, 2025, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.Phaser;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.concurrent.locks.Condition;
|
||||
import java.util.concurrent.locks.Lock;
|
||||
import java.util.concurrent.locks.Condition;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* @test
|
||||
* @bug 8066859
|
||||
* @summary Check that AQS-based locks, conditions, and CountDownLatches do not fail when encountering OOME
|
||||
* @requires vm.gc.G1
|
||||
* @requires test.thread.factory == null
|
||||
* @requires !(vm.graal.enabled & vm.compMode == "Xcomp")
|
||||
* @run main/othervm -XX:+UseG1GC -XX:-UseGCOverheadLimit -Xmx48M -XX:-UseTLAB OOMEInAQS
|
||||
*/
|
||||
|
||||
public class OOMEInAQS extends Thread {
|
||||
static final int NTHREADS = 2; // intentionally not a scalable test; > 2 is very slow
|
||||
static final int NREPS = 100;
|
||||
// statically allocate
|
||||
static final ReentrantLock mainLock = new ReentrantLock();
|
||||
static final Condition condition = mainLock.newCondition();
|
||||
static final CountDownLatch started = new CountDownLatch(1);
|
||||
static final CountDownLatch filled = new CountDownLatch(1);
|
||||
static final CountDownLatch canFill = new CountDownLatch(NTHREADS);
|
||||
static volatile Object data;
|
||||
static volatile Throwable exception;
|
||||
static int turn;
|
||||
|
||||
/**
|
||||
* For each of NTHREADS threads, REPS times: Take turns
|
||||
* executing. Introduce OOM using fillHeap during runs. In
|
||||
* addition to testing AQS, the CountDownLatches ensure that
|
||||
* methods execute at least once before OutOfMemory occurs, to
|
||||
* avoid uncontrollable impact of OOME during class-loading.
|
||||
*/
|
||||
public static void main(String[] args) throws Throwable {
|
||||
OOMEInAQS[] threads = new OOMEInAQS[NTHREADS];
|
||||
for (int i = 0; i < NTHREADS; ++i)
|
||||
(threads[i] = new OOMEInAQS(i)).start();
|
||||
started.countDown();
|
||||
canFill.await();
|
||||
long t0 = System.nanoTime();
|
||||
data = fillHeap();
|
||||
filled.countDown();
|
||||
long t1 = System.nanoTime();
|
||||
for (int i = 0; i < NTHREADS; ++i)
|
||||
threads[i].join();
|
||||
data = null; // free heap before reporting and terminating
|
||||
System.gc();
|
||||
Throwable ex = exception;
|
||||
if (ex != null)
|
||||
throw ex;
|
||||
System.out.println(
|
||||
"fillHeap time: " + (t1 - t0) / 1000_000 +
|
||||
" millis, whole test time: " + (System.nanoTime() - t0) / 1000_000 +
|
||||
" millis"
|
||||
);
|
||||
}
|
||||
|
||||
final int tid;
|
||||
OOMEInAQS(int tid) {
|
||||
this.tid = tid;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
int id = tid, nextId = (id + 1) % NTHREADS;
|
||||
final ReentrantLock lock = mainLock;
|
||||
final Condition cond = condition;
|
||||
try {
|
||||
started.await();
|
||||
for (int i = 0; i < NREPS; i++) {
|
||||
lock.lock();
|
||||
try {
|
||||
while (turn != id)
|
||||
cond.await();
|
||||
turn = nextId;
|
||||
cond.signalAll();
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
if (i == 2) { // Subsequent AQS methods encounter OOME
|
||||
canFill.countDown();
|
||||
filled.await();
|
||||
}
|
||||
}
|
||||
data = null;
|
||||
System.gc(); // avoid getting stuck while exiting
|
||||
} catch (Throwable ex) {
|
||||
data = null;
|
||||
System.gc(); // avoid nested OOME
|
||||
exception = ex;
|
||||
}
|
||||
}
|
||||
|
||||
static Object[] fillHeap() {
|
||||
Object[] first = null, last = null;
|
||||
int size = 1 << 20;
|
||||
while (size > 0) {
|
||||
try {
|
||||
Object[] array = new Object[size];
|
||||
if (first == null) {
|
||||
first = array;
|
||||
} else {
|
||||
last[0] = array;
|
||||
}
|
||||
last = array;
|
||||
} catch (OutOfMemoryError oome) {
|
||||
size = size >>> 1;
|
||||
}
|
||||
}
|
||||
return first;
|
||||
}
|
||||
}
|
||||
43
test/jdk/java/util/concurrent/locks/Lock/TimedAcquire.java
Normal file
43
test/jdk/java/util/concurrent/locks/Lock/TimedAcquire.java
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
/*
|
||||
* Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
/* @test
|
||||
* @bug 6241823
|
||||
* @summary Repeated timed tryAcquire shouldn't hang.
|
||||
*/
|
||||
|
||||
import java.util.concurrent.Semaphore;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class TimedAcquire {
|
||||
public static void main(String[] args) throws Exception {
|
||||
for (Semaphore sem : new Semaphore[]{ new Semaphore(0),
|
||||
new Semaphore(0, false),
|
||||
new Semaphore(0, true)})
|
||||
for (int delay : new int[] {0, 1})
|
||||
for (int i = 0; i < 3; i++)
|
||||
if (sem.tryAcquire(delay, TimeUnit.MILLISECONDS))
|
||||
throw new Error("Acquired Semaphore with no permits!");
|
||||
System.out.println("Done!");
|
||||
}
|
||||
}
|
||||
345
test/jdk/java/util/concurrent/locks/Lock/TimedAcquireLeak.java
Normal file
345
test/jdk/java/util/concurrent/locks/Lock/TimedAcquireLeak.java
Normal file
|
|
@ -0,0 +1,345 @@
|
|||
/*
|
||||
* Copyright (c) 2007, 2018, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
/*
|
||||
* @test
|
||||
* @bug 6460501 6236036 6500694 6490770
|
||||
* @summary Repeated failed timed waits shouldn't leak memory
|
||||
* @library /test/lib
|
||||
* @author Martin Buchholz
|
||||
*/
|
||||
|
||||
import static java.util.concurrent.TimeUnit.MILLISECONDS;
|
||||
import static java.util.concurrent.TimeUnit.NANOSECONDS;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.OutputStream;
|
||||
import java.io.PrintStream;
|
||||
import java.io.Reader;
|
||||
import java.lang.ref.ReferenceQueue;
|
||||
import java.lang.ref.WeakReference;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.Callable;
|
||||
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.LinkedBlockingQueue;
|
||||
import java.util.concurrent.Semaphore;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
import java.util.concurrent.locks.ReentrantReadWriteLock;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import jdk.test.lib.Utils;
|
||||
|
||||
public class TimedAcquireLeak {
|
||||
static final long LONG_DELAY_MS = Utils.adjustTimeout(10_000);
|
||||
|
||||
static String javahome() {
|
||||
String jh = System.getProperty("java.home");
|
||||
return (jh.endsWith("jre")) ? jh.substring(0, jh.length() - 4) : jh;
|
||||
}
|
||||
|
||||
static final File bin = new File(javahome(), "bin");
|
||||
|
||||
static String javaProgramPath(String programName) {
|
||||
return new File(bin, programName).getPath();
|
||||
}
|
||||
|
||||
static final String javaPath = javaProgramPath("java");
|
||||
static final String jmapPath = javaProgramPath("jmap");
|
||||
static final String jpsPath = javaProgramPath("jps");
|
||||
|
||||
static String outputOf(Reader r) throws IOException {
|
||||
final StringBuilder sb = new StringBuilder();
|
||||
final char[] buf = new char[1024];
|
||||
int n;
|
||||
while ((n = r.read(buf)) > 0)
|
||||
sb.append(buf, 0, n);
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
static String outputOf(InputStream is) throws IOException {
|
||||
return outputOf(new InputStreamReader(is, "UTF-8"));
|
||||
}
|
||||
|
||||
static final ExecutorService drainers = Executors.newFixedThreadPool(12);
|
||||
static Future<String> futureOutputOf(final InputStream is) {
|
||||
return drainers.submit(
|
||||
new Callable<String>() { public String call() throws IOException {
|
||||
return outputOf(is); }});}
|
||||
|
||||
static String outputOf(final Process p) {
|
||||
try {
|
||||
Future<String> outputFuture = futureOutputOf(p.getInputStream());
|
||||
Future<String> errorFuture = futureOutputOf(p.getErrorStream());
|
||||
final String output = outputFuture.get();
|
||||
final String error = errorFuture.get();
|
||||
// Check for successful process completion
|
||||
equal(error, "");
|
||||
equal(p.waitFor(), 0);
|
||||
equal(p.exitValue(), 0);
|
||||
return output;
|
||||
} catch (Throwable t) { unexpected(t); throw new Error(t); }
|
||||
}
|
||||
|
||||
static String commandOutputOf(String... cmd) {
|
||||
try { return outputOf(new ProcessBuilder(cmd).start()); }
|
||||
catch (Throwable t) { unexpected(t); throw new Error(t); }
|
||||
}
|
||||
|
||||
// To be called exactly twice by the parent process
|
||||
static <T> T rendezvousParent(Process p,
|
||||
Callable<T> callable) throws Throwable {
|
||||
p.getInputStream().read();
|
||||
T result = callable.call();
|
||||
sendByte(p.getOutputStream());
|
||||
return result;
|
||||
}
|
||||
|
||||
/** No guarantees, but effective in practice. */
|
||||
private static void forceFullGc() {
|
||||
long timeoutMillis = 1000L;
|
||||
CountDownLatch finalized = new CountDownLatch(1);
|
||||
ReferenceQueue<Object> queue = new ReferenceQueue<>();
|
||||
WeakReference<Object> ref = new WeakReference<>(
|
||||
new Object() { protected void finalize() { finalized.countDown(); }},
|
||||
queue);
|
||||
try {
|
||||
for (int tries = 3; tries--> 0; ) {
|
||||
System.gc();
|
||||
if (finalized.await(timeoutMillis, MILLISECONDS)
|
||||
&& queue.remove(timeoutMillis) != null
|
||||
&& ref.get() == null) {
|
||||
System.runFinalization(); // try to pick up stragglers
|
||||
return;
|
||||
}
|
||||
timeoutMillis *= 4;
|
||||
}
|
||||
} catch (InterruptedException unexpected) {
|
||||
throw new AssertionError("unexpected InterruptedException");
|
||||
}
|
||||
throw new AssertionError("failed to do a \"full\" gc");
|
||||
}
|
||||
|
||||
// To be called exactly twice by the child process
|
||||
public static void rendezvousChild() {
|
||||
try {
|
||||
forceFullGc();
|
||||
sendByte(System.out);
|
||||
System.in.read();
|
||||
} catch (Throwable t) { throw new Error(t); }
|
||||
}
|
||||
|
||||
static String match(String s, String regex, int group) {
|
||||
Matcher matcher = Pattern.compile(regex).matcher(s);
|
||||
if (! matcher.find()) {
|
||||
String msg = String.format(
|
||||
"match failed: s=%s regex=%s", s, regex);
|
||||
throw new AssertionError(msg);
|
||||
}
|
||||
return matcher.group(group);
|
||||
}
|
||||
|
||||
/** It's all about sending a message! */
|
||||
static void sendByte(OutputStream s) throws IOException {
|
||||
s.write('!');
|
||||
s.flush();
|
||||
}
|
||||
|
||||
static int objectsInUse(final Process child,
|
||||
final String childPid,
|
||||
final String classNameRegex) {
|
||||
String regex =
|
||||
"(?m)^ *[0-9]+: +([0-9]+) +[0-9]+ +"+classNameRegex+"(?:$| )";
|
||||
Callable<Integer> objectsInUse = () -> {
|
||||
int i = Integer.parseInt(
|
||||
match(commandOutputOf(jmapPath, "-histo:live", childPid),
|
||||
regex, 1));
|
||||
if (i > 100)
|
||||
System.out.print(
|
||||
commandOutputOf(jmapPath,
|
||||
"-dump:file=dump,format=b",
|
||||
childPid));
|
||||
return i;
|
||||
};
|
||||
try { return rendezvousParent(child, objectsInUse); }
|
||||
catch (Throwable t) { unexpected(t); return -1; }
|
||||
}
|
||||
|
||||
static void realMain(String[] args) throws Throwable {
|
||||
// jmap doesn't work on Windows
|
||||
if (System.getProperty("os.name").startsWith("Windows"))
|
||||
return;
|
||||
|
||||
final String childClassName = Job.class.getName();
|
||||
final String classNameRegex = Job.classNameRegexToCheckForLeaks();
|
||||
final String uniqueID = String.valueOf(
|
||||
ThreadLocalRandom.current().nextInt(Integer.MAX_VALUE));
|
||||
|
||||
final ArrayList<String> jobCmd = new ArrayList<>();
|
||||
Collections.addAll(
|
||||
jobCmd, javaPath, "-Xmx8m", "-XX:+UsePerfData",
|
||||
"-classpath", System.getProperty("test.class.path"));
|
||||
Collections.addAll(jobCmd, Utils.getTestJavaOpts());
|
||||
Collections.addAll(jobCmd, childClassName, uniqueID);
|
||||
final Process p = new ProcessBuilder(jobCmd).start();
|
||||
// Ensure subprocess jvm has started, so that jps can find it
|
||||
p.getInputStream().read();
|
||||
sendByte(p.getOutputStream());
|
||||
|
||||
final String childPid =
|
||||
match(commandOutputOf(jpsPath, "-m"),
|
||||
"(?m)^ *([0-9]+) +\\Q"+childClassName+"\\E *"+uniqueID+"$", 1);
|
||||
|
||||
final int n0 = objectsInUse(p, childPid, classNameRegex);
|
||||
final int n1 = objectsInUse(p, childPid, classNameRegex);
|
||||
equal(p.waitFor(), 0);
|
||||
equal(p.exitValue(), 0);
|
||||
failed += p.exitValue();
|
||||
|
||||
// Check that no objects were leaked.
|
||||
//
|
||||
// TODO: This test is very brittle, depending on current JDK
|
||||
// implementation, and needing occasional adjustment.
|
||||
System.out.printf("%d -> %d%n", n0, n1);
|
||||
// Almost always n0 == n1
|
||||
// Maximum jitter observed in practice is 7
|
||||
check(Math.abs(n1 - n0) < 10);
|
||||
check(n1 < 25);
|
||||
drainers.shutdown();
|
||||
if (!drainers.awaitTermination(LONG_DELAY_MS, MILLISECONDS)) {
|
||||
drainers.shutdownNow(); // last resort
|
||||
throw new AssertionError("thread pool did not terminate");
|
||||
}
|
||||
}
|
||||
|
||||
//----------------------------------------------------------------
|
||||
// The main class of the child process.
|
||||
// Job's job is to:
|
||||
// - provide the name of a class to check for leaks.
|
||||
// - call rendezvousChild exactly twice, while quiescent.
|
||||
// - in between calls to rendezvousChild, run code that may leak.
|
||||
//----------------------------------------------------------------
|
||||
public static class Job {
|
||||
static String classNameRegexToCheckForLeaks() {
|
||||
return
|
||||
"\\Qjava.util.concurrent.locks.AbstractQueuedSynchronizer$\\E[A-Za-z]+";
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
// Synchronize with parent process, so that jps can find us
|
||||
sendByte(System.out);
|
||||
System.in.read();
|
||||
|
||||
final ReentrantLock lock = new ReentrantLock();
|
||||
lock.lock();
|
||||
|
||||
final ReentrantReadWriteLock rwlock
|
||||
= new ReentrantReadWriteLock();
|
||||
final ReentrantReadWriteLock.ReadLock readLock
|
||||
= rwlock.readLock();
|
||||
final ReentrantReadWriteLock.WriteLock writeLock
|
||||
= rwlock.writeLock();
|
||||
rwlock.writeLock().lock();
|
||||
|
||||
final BlockingQueue<Object> q = new LinkedBlockingQueue<>();
|
||||
final Semaphore fairSem = new Semaphore(0, true);
|
||||
final Semaphore unfairSem = new Semaphore(0, false);
|
||||
//final int threads =
|
||||
//rnd.nextInt(Runtime.getRuntime().availableProcessors() + 1) + 1;
|
||||
final int threads = 3;
|
||||
// On Linux, this test runs very slowly for some reason,
|
||||
// so use a smaller number of iterations.
|
||||
// Solaris can handle 1 << 18.
|
||||
// On the other hand, jmap is much slower on Solaris...
|
||||
final int iterations = 1 << 8;
|
||||
final CyclicBarrier cb = new CyclicBarrier(threads+1);
|
||||
|
||||
for (int i = 0; i < threads; i++)
|
||||
new Thread() { public void run() {
|
||||
try {
|
||||
final ThreadLocalRandom rnd = ThreadLocalRandom.current();
|
||||
for (int j = 0; j < iterations; j++) {
|
||||
if (j == iterations/10 || j == iterations - 1) {
|
||||
cb.await(); // Quiesce
|
||||
cb.await(); // Resume
|
||||
}
|
||||
//int t = rnd.nextInt(2000);
|
||||
int t = rnd.nextInt(900);
|
||||
check(! lock.tryLock(t, NANOSECONDS));
|
||||
check(! readLock.tryLock(t, NANOSECONDS));
|
||||
check(! writeLock.tryLock(t, NANOSECONDS));
|
||||
equal(null, q.poll(t, NANOSECONDS));
|
||||
check(! fairSem.tryAcquire(t, NANOSECONDS));
|
||||
check(! unfairSem.tryAcquire(t, NANOSECONDS));
|
||||
}
|
||||
} catch (Throwable t) { unexpected(t); }
|
||||
}}.start();
|
||||
|
||||
cb.await(); // Quiesce
|
||||
rendezvousChild(); // Measure
|
||||
cb.await(); // Resume
|
||||
|
||||
cb.await(); // Quiesce
|
||||
rendezvousChild(); // Measure
|
||||
cb.await(); // Resume
|
||||
|
||||
System.exit(failed);
|
||||
}
|
||||
|
||||
// If something goes wrong, we might never see it, since IO
|
||||
// streams are connected to the parent. So we need a special
|
||||
// purpose print method to debug Jobs.
|
||||
static void debugPrintf(String format, Object... args) {
|
||||
try {
|
||||
new PrintStream(new FileOutputStream("/dev/tty"))
|
||||
.printf(format, args);
|
||||
} catch (Throwable t) { throw new Error(t); }
|
||||
}
|
||||
}
|
||||
|
||||
//--------------------- Infrastructure ---------------------------
|
||||
static volatile int passed = 0, failed = 0;
|
||||
static void pass() {passed++;}
|
||||
static void fail() {failed++; Thread.dumpStack();}
|
||||
static void fail(String msg) {System.out.println(msg); fail();}
|
||||
static void unexpected(Throwable t) {failed++; t.printStackTrace();}
|
||||
static void check(boolean cond) {if (cond) pass(); else fail();}
|
||||
static void check(boolean cond, String m) {if (cond) pass(); else fail(m);}
|
||||
static void equal(Object x, Object y) {
|
||||
if (x == null ? y == null : x.equals(y)) pass();
|
||||
else fail(x + " not equal to " + y);}
|
||||
public static void main(String[] args) throws Throwable {
|
||||
try {realMain(args);} catch (Throwable t) {unexpected(t);}
|
||||
System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
|
||||
if (failed > 0) throw new AssertionError("Some tests failed");}
|
||||
}
|
||||
128
test/jdk/java/util/concurrent/locks/LockSupport/ParkLoops.java
Normal file
128
test/jdk/java/util/concurrent/locks/LockSupport/ParkLoops.java
Normal file
|
|
@ -0,0 +1,128 @@
|
|||
/*
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
/*
|
||||
* This file is available under and governed by the GNU General Public
|
||||
* License version 2 only, as published by the Free Software Foundation.
|
||||
* However, the following notice accompanied the original version of this
|
||||
* file:
|
||||
*
|
||||
* Written by Martin Buchholz with assistance from members of JCP
|
||||
* JSR-166 Expert Group and released to the public domain, as
|
||||
* explained at http://creativecommons.org/publicdomain/zero/1.0/
|
||||
*/
|
||||
|
||||
/*
|
||||
* @test
|
||||
* @bug 8074773
|
||||
* @summary Stress test looks for lost unparks
|
||||
*/
|
||||
|
||||
import static java.util.concurrent.TimeUnit.SECONDS;
|
||||
|
||||
import java.util.SplittableRandom;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.atomic.AtomicReferenceArray;
|
||||
import java.util.concurrent.locks.LockSupport;
|
||||
|
||||
public final class ParkLoops {
|
||||
static final int THREADS = 4;
|
||||
static final int ITERS = 30_000;
|
||||
|
||||
static class Parker implements Runnable {
|
||||
static {
|
||||
// Reduce the risk of rare disastrous classloading in first call to
|
||||
// LockSupport.park: https://bugs.openjdk.org/browse/JDK-8074773
|
||||
Class<?> ensureLoaded = LockSupport.class;
|
||||
}
|
||||
|
||||
private final AtomicReferenceArray<Thread> threads;
|
||||
private final CountDownLatch done;
|
||||
private final SplittableRandom rnd;
|
||||
|
||||
Parker(AtomicReferenceArray<Thread> threads,
|
||||
CountDownLatch done,
|
||||
SplittableRandom rnd) {
|
||||
this.threads = threads; this.done = done; this.rnd = rnd;
|
||||
}
|
||||
|
||||
public void run() {
|
||||
final Thread current = Thread.currentThread();
|
||||
for (int k = ITERS, j; k > 0; k--) {
|
||||
do {
|
||||
j = rnd.nextInt(THREADS);
|
||||
} while (!threads.compareAndSet(j, null, current));
|
||||
do { // handle spurious wakeups
|
||||
LockSupport.park();
|
||||
} while (threads.get(j) == current);
|
||||
}
|
||||
done.countDown();
|
||||
}
|
||||
}
|
||||
|
||||
static class Unparker implements Runnable {
|
||||
static {
|
||||
// Reduce the risk of rare disastrous classloading in first call to
|
||||
// LockSupport.park: https://bugs.openjdk.org/browse/JDK-8074773
|
||||
Class<?> ensureLoaded = LockSupport.class;
|
||||
}
|
||||
|
||||
private final AtomicReferenceArray<Thread> threads;
|
||||
private final CountDownLatch done;
|
||||
private final SplittableRandom rnd;
|
||||
|
||||
Unparker(AtomicReferenceArray<Thread> threads,
|
||||
CountDownLatch done,
|
||||
SplittableRandom rnd) {
|
||||
this.threads = threads; this.done = done; this.rnd = rnd;
|
||||
}
|
||||
|
||||
public void run() {
|
||||
for (int n = 0; (n++ & 0xff) != 0 || done.getCount() > 0;) {
|
||||
int j = rnd.nextInt(THREADS);
|
||||
Thread parker = threads.get(j);
|
||||
if (parker != null &&
|
||||
threads.compareAndSet(j, parker, null)) {
|
||||
LockSupport.unpark(parker);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
for (int i = 0; i < THREADS; i++) {
|
||||
pool.submit(new Parker(threads, done, rnd.split()));
|
||||
pool.submit(new Unparker(threads, done, rnd.split()));
|
||||
}
|
||||
// Let test harness handle timeout
|
||||
done.await();
|
||||
pool.shutdown();
|
||||
pool.awaitTermination(Long.MAX_VALUE, SECONDS);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,164 @@
|
|||
/*
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
/*
|
||||
* This file is available under and governed by the GNU General Public
|
||||
* License version 2 only, as published by the Free Software Foundation.
|
||||
* However, the following notice accompanied the original version of this
|
||||
* file:
|
||||
*
|
||||
* Written by Doug Lea with assistance from members of JCP JSR-166
|
||||
* Expert Group and released to the public domain, as explained at
|
||||
* http://creativecommons.org/publicdomain/zero/1.0/
|
||||
*/
|
||||
|
||||
/*
|
||||
* @test
|
||||
* @bug 4486658 8040928 8140468
|
||||
* @summary tests ReentrantLock.lockInterruptibly.
|
||||
* Checks for responsiveness of locks to interrupts.
|
||||
*/
|
||||
|
||||
import static java.util.concurrent.TimeUnit.NANOSECONDS;
|
||||
|
||||
import java.util.concurrent.CyclicBarrier;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
|
||||
public final class CancelledLockLoops {
|
||||
public static void main(String[] args) throws Exception {
|
||||
final int maxThreads = (args.length > 0) ? Integer.parseInt(args[0]) : 5;
|
||||
final int reps = 1; // increase for stress testing
|
||||
|
||||
for (int j = 0; j < reps; j++) {
|
||||
for (int i = 2; i <= maxThreads; i += (i+1) >>> 1) {
|
||||
new Loops(i).test();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static final class Loops implements Runnable {
|
||||
private final boolean print = false;
|
||||
private volatile boolean done = false;
|
||||
private int v = ThreadLocalRandom.current().nextInt();
|
||||
private int completed = 0;
|
||||
private volatile int result = 17;
|
||||
private final ReentrantLock lock = new ReentrantLock();
|
||||
private final LoopHelpers.BarrierTimer timer = new LoopHelpers.BarrierTimer();
|
||||
private final CyclicBarrier barrier;
|
||||
private final int nthreads;
|
||||
private volatile Throwable fail = null;
|
||||
Loops(int nthreads) {
|
||||
this.nthreads = nthreads;
|
||||
if (print) System.out.print("Threads: " + nthreads);
|
||||
barrier = new CyclicBarrier(nthreads+1, timer);
|
||||
}
|
||||
|
||||
final void test() throws Exception {
|
||||
final ThreadLocalRandom rnd = ThreadLocalRandom.current();
|
||||
Thread[] threads = new Thread[nthreads];
|
||||
for (int i = 0; i < threads.length; ++i)
|
||||
threads[i] = new Thread(this);
|
||||
for (int i = 0; i < threads.length; ++i)
|
||||
threads[i].start();
|
||||
Thread[] cancels = threads.clone();
|
||||
barrier.await();
|
||||
Thread.sleep(rnd.nextInt(5));
|
||||
for (int i = 0; i < cancels.length-2; ++i) {
|
||||
cancels[i].interrupt();
|
||||
// make sure all OK even when cancellations spaced out
|
||||
if ( (i & 3) == 0)
|
||||
Thread.sleep(1 + rnd.nextInt(5));
|
||||
}
|
||||
done = true;
|
||||
barrier.await();
|
||||
if (print) {
|
||||
long time = timer.getTime();
|
||||
double secs = (double)time / 1000000000.0;
|
||||
System.out.println("\t " + secs + "s run time");
|
||||
}
|
||||
|
||||
int c;
|
||||
lock.lock();
|
||||
try {
|
||||
c = completed;
|
||||
}
|
||||
finally {
|
||||
lock.unlock();
|
||||
}
|
||||
if (c != 2)
|
||||
throw new Error("Completed == " + c + "; expected 2");
|
||||
int r = result;
|
||||
if (r == 0) // avoid overoptimization
|
||||
System.out.println("useless result: " + r);
|
||||
if (fail != null) throw new RuntimeException(fail);
|
||||
}
|
||||
|
||||
public final void run() {
|
||||
try {
|
||||
barrier.await();
|
||||
boolean interrupted = false;
|
||||
long startTime = System.nanoTime();
|
||||
int sum = v;
|
||||
int x = 0;
|
||||
while (!done || Thread.currentThread().isInterrupted()) {
|
||||
try {
|
||||
lock.lockInterruptibly();
|
||||
}
|
||||
catch (InterruptedException ie) {
|
||||
interrupted = true;
|
||||
if (print)
|
||||
System.out.printf("interrupted after %d millis%n",
|
||||
NANOSECONDS.toMillis(System.nanoTime() - startTime));
|
||||
break;
|
||||
}
|
||||
try {
|
||||
v = x = LoopHelpers.compute1(v);
|
||||
}
|
||||
finally {
|
||||
lock.unlock();
|
||||
}
|
||||
sum += LoopHelpers.compute2(x);
|
||||
}
|
||||
if (!interrupted) {
|
||||
if (print)
|
||||
System.out.printf("completed after %d millis%n",
|
||||
NANOSECONDS.toMillis(System.nanoTime() - startTime));
|
||||
lock.lock();
|
||||
try {
|
||||
++completed;
|
||||
}
|
||||
finally {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
barrier.await();
|
||||
result += sum;
|
||||
}
|
||||
catch (Throwable ex) {
|
||||
fail = ex;
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,135 @@
|
|||
/*
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
/*
|
||||
* This file is available under and governed by the GNU General Public
|
||||
* License version 2 only, as published by the Free Software Foundation.
|
||||
* However, the following notice accompanied the original version of this
|
||||
* file:
|
||||
*
|
||||
* Written by Doug Lea with assistance from members of JCP JSR-166
|
||||
* Expert Group and released to the public domain, as explained at
|
||||
* http://creativecommons.org/publicdomain/zero/1.0/
|
||||
*/
|
||||
|
||||
/*
|
||||
* @test
|
||||
* @bug 4486658
|
||||
* @summary Checks for missed signals by locking and unlocking each of an array of locks once per thread
|
||||
* @library /test/lib
|
||||
*/
|
||||
|
||||
import static java.util.concurrent.TimeUnit.MILLISECONDS;
|
||||
|
||||
import java.util.concurrent.CyclicBarrier;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
import jdk.test.lib.Utils;
|
||||
|
||||
public final class LockOncePerThreadLoops {
|
||||
static final long LONG_DELAY_MS = Utils.adjustTimeout(10_000);
|
||||
static final ExecutorService pool = Executors.newCachedThreadPool();
|
||||
static boolean print = false;
|
||||
static int nlocks = 20_000;
|
||||
static int nthreads = 20;
|
||||
static int replications = 3;
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
if (args.length > 0)
|
||||
replications = Integer.parseInt(args[0]);
|
||||
|
||||
if (args.length > 1)
|
||||
nlocks = Integer.parseInt(args[1]);
|
||||
|
||||
print = true;
|
||||
|
||||
for (int i = 0; i < replications; ++i) {
|
||||
System.out.print("Iteration: " + i);
|
||||
new ReentrantLockLoop().test();
|
||||
}
|
||||
pool.shutdown();
|
||||
if (! pool.awaitTermination(LONG_DELAY_MS, MILLISECONDS))
|
||||
throw new Error();
|
||||
}
|
||||
|
||||
static final class ReentrantLockLoop implements Runnable {
|
||||
private int v = ThreadLocalRandom.current().nextInt();
|
||||
private volatile int result = 17;
|
||||
final ReentrantLock[]locks = new ReentrantLock[nlocks];
|
||||
|
||||
private final ReentrantLock lock = new ReentrantLock();
|
||||
private final LoopHelpers.BarrierTimer timer = new LoopHelpers.BarrierTimer();
|
||||
private final CyclicBarrier barrier;
|
||||
ReentrantLockLoop() {
|
||||
barrier = new CyclicBarrier(nthreads+1, timer);
|
||||
for (int i = 0; i < nlocks; ++i)
|
||||
locks[i] = new ReentrantLock();
|
||||
}
|
||||
|
||||
final void test() throws Exception {
|
||||
for (int i = 0; i < nthreads; ++i)
|
||||
pool.execute(this);
|
||||
barrier.await();
|
||||
barrier.await();
|
||||
if (print) {
|
||||
long time = timer.getTime();
|
||||
double secs = (double)time / 1000000000.0;
|
||||
System.out.println("\t " + secs + "s run time");
|
||||
}
|
||||
|
||||
int r = result;
|
||||
if (r == 0) // avoid overoptimization
|
||||
System.out.println("useless result: " + r);
|
||||
}
|
||||
|
||||
public final void run() {
|
||||
try {
|
||||
barrier.await();
|
||||
int sum = v;
|
||||
int x = 0;
|
||||
for (int i = 0; i < locks.length; ++i) {
|
||||
locks[i].lock();
|
||||
try {
|
||||
v = x += ~(v - i);
|
||||
}
|
||||
finally {
|
||||
locks[i].unlock();
|
||||
}
|
||||
// Once in a while, do something more expensive
|
||||
if ((~i & 255) == 0) {
|
||||
sum += LoopHelpers.compute1(LoopHelpers.compute2(x));
|
||||
}
|
||||
else
|
||||
sum += sum ^ x;
|
||||
}
|
||||
barrier.await();
|
||||
result += sum;
|
||||
}
|
||||
catch (Exception ex) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,103 @@
|
|||
/*
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
/*
|
||||
* This file is available under and governed by the GNU General Public
|
||||
* License version 2 only, as published by the Free Software Foundation.
|
||||
* However, the following notice accompanied the original version of this
|
||||
* file:
|
||||
*
|
||||
* Written by Doug Lea with assistance from members of JCP JSR-166
|
||||
* Expert Group and released to the public domain, as explained at
|
||||
* http://creativecommons.org/publicdomain/zero/1.0/
|
||||
*/
|
||||
|
||||
/**
|
||||
* Misc utilities in JSR166 performance tests
|
||||
*/
|
||||
class LoopHelpers {
|
||||
|
||||
// Some mindless computation to do between synchronizations...
|
||||
|
||||
/**
|
||||
* generates 32 bit pseudo-random numbers.
|
||||
* Adapted from http://www.snippets.org
|
||||
*/
|
||||
public static int compute1(int x) {
|
||||
int lo = 16807 * (x & 0xFFFF);
|
||||
int hi = 16807 * (x >>> 16);
|
||||
lo += (hi & 0x7FFF) << 16;
|
||||
if ((lo & 0x80000000) != 0) {
|
||||
lo &= 0x7fffffff;
|
||||
++lo;
|
||||
}
|
||||
lo += hi >>> 15;
|
||||
if (lo == 0 || (lo & 0x80000000) != 0) {
|
||||
lo &= 0x7fffffff;
|
||||
++lo;
|
||||
}
|
||||
return lo;
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes a linear congruential random number a random number
|
||||
* of times.
|
||||
*/
|
||||
public static int compute2(int x) {
|
||||
int loops = (x >>> 4) & 7;
|
||||
while (loops-- > 0) {
|
||||
x = (x * 2147483647) % 16807;
|
||||
}
|
||||
return x;
|
||||
}
|
||||
|
||||
public static class BarrierTimer implements Runnable {
|
||||
public volatile long startTime;
|
||||
public volatile long endTime;
|
||||
public void run() {
|
||||
long t = System.nanoTime();
|
||||
if (startTime == 0)
|
||||
startTime = t;
|
||||
else
|
||||
endTime = t;
|
||||
}
|
||||
public void clear() {
|
||||
startTime = 0;
|
||||
endTime = 0;
|
||||
}
|
||||
public long getTime() {
|
||||
return endTime - startTime;
|
||||
}
|
||||
}
|
||||
|
||||
public static String rightJustify(long n) {
|
||||
// There's probably a better way to do this...
|
||||
String field = " ";
|
||||
String num = Long.toString(n);
|
||||
if (num.length() >= field.length())
|
||||
return num;
|
||||
StringBuilder b = new StringBuilder(field);
|
||||
b.replace(b.length()-num.length(), b.length(), num);
|
||||
return b.toString();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,140 @@
|
|||
/*
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
/*
|
||||
* This file is available under and governed by the GNU General Public
|
||||
* License version 2 only, as published by the Free Software Foundation.
|
||||
* However, the following notice accompanied the original version of this
|
||||
* file:
|
||||
*
|
||||
* Written by Doug Lea with assistance from members of JCP JSR-166
|
||||
* Expert Group and released to the public domain, as explained at
|
||||
* http://creativecommons.org/publicdomain/zero/1.0/
|
||||
*/
|
||||
|
||||
/*
|
||||
* @test
|
||||
* @bug 4486658
|
||||
* @summary multiple threads using a single lock
|
||||
* @library /test/lib
|
||||
*/
|
||||
|
||||
import static java.util.concurrent.TimeUnit.MILLISECONDS;
|
||||
|
||||
import java.util.concurrent.CyclicBarrier;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import jdk.test.lib.Utils;
|
||||
|
||||
public final class SimpleReentrantLockLoops {
|
||||
static final long LONG_DELAY_MS = Utils.adjustTimeout(10_000);
|
||||
static final ExecutorService pool = Executors.newCachedThreadPool();
|
||||
static boolean print = false;
|
||||
static int iters = 100_000;
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
int maxThreads = 5;
|
||||
if (args.length > 0)
|
||||
maxThreads = Integer.parseInt(args[0]);
|
||||
|
||||
print = true;
|
||||
|
||||
int reps = 2;
|
||||
for (int i = 1; i <= maxThreads; i += (i+1) >>> 1) {
|
||||
int n = reps;
|
||||
if (reps > 1) --reps;
|
||||
while (n-- > 0) {
|
||||
System.out.print("Threads: " + i);
|
||||
new ReentrantLockLoop(i).test();
|
||||
}
|
||||
}
|
||||
pool.shutdown();
|
||||
if (! pool.awaitTermination(LONG_DELAY_MS, MILLISECONDS))
|
||||
throw new Error();
|
||||
}
|
||||
|
||||
static final class ReentrantLockLoop implements Runnable {
|
||||
private int v = ThreadLocalRandom.current().nextInt();
|
||||
private volatile int result = 17;
|
||||
private final ReentrantLock lock = new ReentrantLock();
|
||||
private final LoopHelpers.BarrierTimer timer = new LoopHelpers.BarrierTimer();
|
||||
private final CyclicBarrier barrier;
|
||||
private final int nthreads;
|
||||
ReentrantLockLoop(int nthreads) {
|
||||
this.nthreads = nthreads;
|
||||
barrier = new CyclicBarrier(nthreads+1, timer);
|
||||
}
|
||||
|
||||
final void test() throws Exception {
|
||||
for (int i = 0; i < nthreads; ++i)
|
||||
pool.execute(this);
|
||||
barrier.await();
|
||||
barrier.await();
|
||||
if (print) {
|
||||
long time = timer.getTime();
|
||||
long tpi = time / ((long)iters * nthreads);
|
||||
System.out.print("\t" + LoopHelpers.rightJustify(tpi) + " ns per lock");
|
||||
double secs = (double)time / 1000000000.0;
|
||||
System.out.println("\t " + secs + "s run time");
|
||||
}
|
||||
|
||||
int r = result;
|
||||
if (r == 0) // avoid overoptimization
|
||||
System.out.println("useless result: " + r);
|
||||
}
|
||||
|
||||
public final void run() {
|
||||
try {
|
||||
barrier.await();
|
||||
int sum = v;
|
||||
int x = 0;
|
||||
int n = iters;
|
||||
do {
|
||||
lock.lock();
|
||||
try {
|
||||
if ((n & 255) == 0)
|
||||
v = x = LoopHelpers.compute2(LoopHelpers.compute1(v));
|
||||
else
|
||||
v = x += ~(v - n);
|
||||
}
|
||||
finally {
|
||||
lock.unlock();
|
||||
}
|
||||
// Once in a while, do something more expensive
|
||||
if ((~n & 255) == 0) {
|
||||
sum += LoopHelpers.compute1(LoopHelpers.compute2(x));
|
||||
}
|
||||
else
|
||||
sum += sum ^ x;
|
||||
} while (n-- > 0);
|
||||
barrier.await();
|
||||
result += sum;
|
||||
}
|
||||
catch (Exception ex) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,133 @@
|
|||
/*
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
/*
|
||||
* This file is available under and governed by the GNU General Public
|
||||
* License version 2 only, as published by the Free Software Foundation.
|
||||
* However, the following notice accompanied the original version of this
|
||||
* file:
|
||||
*
|
||||
* Written by Doug Lea with assistance from members of JCP JSR-166
|
||||
* Expert Group and released to the public domain, as explained at
|
||||
* http://creativecommons.org/publicdomain/zero/1.0/
|
||||
*/
|
||||
|
||||
/*
|
||||
* @test
|
||||
* @bug 4486658 5031862 8140471
|
||||
* @summary Checks for responsiveness of locks to timeouts.
|
||||
* @library /test/lib
|
||||
*/
|
||||
|
||||
import static java.util.concurrent.TimeUnit.MILLISECONDS;
|
||||
|
||||
import java.util.concurrent.CyclicBarrier;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
import jdk.test.lib.Utils;
|
||||
|
||||
public final class TimeoutLockLoops {
|
||||
static final long LONG_DELAY_MS = Utils.adjustTimeout(10_000);
|
||||
static final ExecutorService pool = Executors.newCachedThreadPool();
|
||||
static boolean print = false;
|
||||
static final long TIMEOUT = 10;
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
int maxThreads = 8;
|
||||
if (args.length > 0)
|
||||
maxThreads = Integer.parseInt(args[0]);
|
||||
|
||||
print = true;
|
||||
|
||||
for (int i = 1; i <= maxThreads; i += (i+1) >>> 1) {
|
||||
System.out.print("Threads: " + i);
|
||||
new ReentrantLockLoop(i).test();
|
||||
}
|
||||
pool.shutdown();
|
||||
if (! pool.awaitTermination(LONG_DELAY_MS, MILLISECONDS))
|
||||
throw new Error();
|
||||
}
|
||||
|
||||
static final class ReentrantLockLoop implements Runnable {
|
||||
private int v = ThreadLocalRandom.current().nextInt();
|
||||
private volatile int result = 17;
|
||||
private final ReentrantLock lock = new ReentrantLock();
|
||||
private final LoopHelpers.BarrierTimer timer = new LoopHelpers.BarrierTimer();
|
||||
private final CyclicBarrier barrier;
|
||||
private final int nthreads;
|
||||
private volatile Throwable fail = null;
|
||||
ReentrantLockLoop(int nthreads) {
|
||||
this.nthreads = nthreads;
|
||||
barrier = new CyclicBarrier(nthreads+1, timer);
|
||||
}
|
||||
|
||||
final void test() throws Exception {
|
||||
for (int i = 0; i < nthreads; ++i) {
|
||||
lock.lock();
|
||||
pool.execute(this);
|
||||
lock.unlock();
|
||||
}
|
||||
barrier.await();
|
||||
Thread.sleep(ThreadLocalRandom.current().nextInt(5));
|
||||
while (!lock.tryLock()); // Jam lock
|
||||
// lock.lock();
|
||||
barrier.await();
|
||||
if (print) {
|
||||
long time = timer.getTime();
|
||||
double secs = (double)time / 1000000000.0;
|
||||
System.out.println("\t " + secs + "s run time");
|
||||
}
|
||||
|
||||
int r = result;
|
||||
if (r == 0) // avoid overoptimization
|
||||
System.out.println("useless result: " + r);
|
||||
if (fail != null) throw new RuntimeException(fail);
|
||||
}
|
||||
|
||||
public final void run() {
|
||||
try {
|
||||
barrier.await();
|
||||
int sum = v;
|
||||
int x = 17;
|
||||
final ReentrantLock lock = this.lock;
|
||||
while (lock.tryLock(TIMEOUT, TimeUnit.MILLISECONDS)) {
|
||||
try {
|
||||
v = x = LoopHelpers.compute1(v);
|
||||
}
|
||||
finally {
|
||||
lock.unlock();
|
||||
}
|
||||
sum += LoopHelpers.compute2(x);
|
||||
}
|
||||
barrier.await();
|
||||
result += sum;
|
||||
}
|
||||
catch (Throwable ex) {
|
||||
fail = ex;
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,72 @@
|
|||
/*
|
||||
* Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
/*
|
||||
* @test
|
||||
* @bug 6571733 6460501
|
||||
* @summary Check that regaining a read lock succeeds after a write
|
||||
* lock attempt times out
|
||||
*/
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.locks.ReentrantReadWriteLock;
|
||||
|
||||
public class Bug6571733 {
|
||||
|
||||
void test(String[] args) throws Throwable {
|
||||
test(true);
|
||||
test(false);
|
||||
}
|
||||
|
||||
void test(boolean fairness) throws Throwable {
|
||||
final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fairness);
|
||||
|
||||
// obtain read lock
|
||||
lock.readLock().lock();
|
||||
|
||||
Thread thread = new Thread() { public void run() {
|
||||
try {
|
||||
check(! lock.writeLock().tryLock(0, TimeUnit.DAYS));
|
||||
|
||||
lock.readLock().lock();
|
||||
lock.readLock().unlock();
|
||||
} catch (Throwable t) { unexpected(t); }}};
|
||||
|
||||
thread.start();
|
||||
thread.join();
|
||||
}
|
||||
|
||||
//--------------------- Infrastructure ---------------------------
|
||||
volatile int passed = 0, failed = 0;
|
||||
void pass() {passed++;}
|
||||
void fail() {failed++; Thread.dumpStack();}
|
||||
void fail(String msg) {System.err.println(msg); fail();}
|
||||
void unexpected(Throwable t) {failed++; t.printStackTrace();}
|
||||
void check(boolean cond) {if (cond) pass(); else fail();}
|
||||
public static void main(String[] args) throws Throwable {
|
||||
new Bug6571733().instanceMain(args);}
|
||||
void instanceMain(String[] args) throws Throwable {
|
||||
try {test(args);} catch (Throwable t) {unexpected(t);}
|
||||
System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
|
||||
if (failed > 0) throw new AssertionError("Some tests failed");}
|
||||
}
|
||||
|
|
@ -0,0 +1,208 @@
|
|||
/*
|
||||
* Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
/*
|
||||
* @test
|
||||
* @bug 6207928 6328220 6378321 6625723
|
||||
* @summary Recursive lock invariant sanity checks
|
||||
* @library /test/lib
|
||||
* @author Martin Buchholz
|
||||
*/
|
||||
|
||||
import static java.util.concurrent.TimeUnit.MILLISECONDS;
|
||||
|
||||
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;
|
||||
import jdk.test.lib.Utils;
|
||||
|
||||
// I am the Cownt, and I lahve to cownt.
|
||||
public class Count {
|
||||
static final long LONG_DELAY_MS = Utils.adjustTimeout(10_000);
|
||||
final Random rnd = new Random();
|
||||
|
||||
void lock(Lock lock) {
|
||||
try {
|
||||
switch (rnd.nextInt(4)) {
|
||||
case 0: lock.lock(); break;
|
||||
case 1: lock.lockInterruptibly(); break;
|
||||
case 2: check(lock.tryLock()); break;
|
||||
case 3: check(lock.tryLock(45, TimeUnit.MINUTES)); break;
|
||||
}
|
||||
} catch (Throwable t) { unexpected(t); }
|
||||
}
|
||||
|
||||
void test(String[] args) throws Throwable {
|
||||
for (boolean fair : new boolean[] { true, false })
|
||||
for (boolean serialClone : new boolean[] { true, false }) {
|
||||
testReentrantLocks(fair, serialClone);
|
||||
testConcurrentReadLocks(fair, serialClone);
|
||||
}
|
||||
}
|
||||
|
||||
void testConcurrentReadLocks(final boolean fair,
|
||||
final boolean serialClone) throws Throwable {
|
||||
final int nThreads = 10;
|
||||
final CyclicBarrier barrier = new CyclicBarrier(nThreads);
|
||||
final ExecutorService es = Executors.newFixedThreadPool(nThreads);
|
||||
final ReentrantReadWriteLock rwl = serialClone ?
|
||||
serialClone(new ReentrantReadWriteLock(fair)) :
|
||||
new ReentrantReadWriteLock(fair);
|
||||
for (int i = 0; i < nThreads; i++) {
|
||||
es.submit(new Runnable() { public void run() {
|
||||
try {
|
||||
int n = 5;
|
||||
for (int i = 0; i < n; i++) {
|
||||
barrier.await();
|
||||
equal(rwl.getReadHoldCount(), i);
|
||||
equal(rwl.getWriteHoldCount(), 0);
|
||||
check(! rwl.isWriteLocked());
|
||||
equal(rwl.getReadLockCount(), nThreads * i);
|
||||
barrier.await();
|
||||
lock(rwl.readLock());
|
||||
}
|
||||
for (int i = 0; i < n; i++) {
|
||||
rwl.readLock().unlock();
|
||||
barrier.await();
|
||||
equal(rwl.getReadHoldCount(), n-i-1);
|
||||
equal(rwl.getReadLockCount(), nThreads*(n-i-1));
|
||||
equal(rwl.getWriteHoldCount(), 0);
|
||||
check(! rwl.isWriteLocked());
|
||||
barrier.await();
|
||||
}
|
||||
THROWS(IllegalMonitorStateException.class,
|
||||
new F(){void f(){rwl.readLock().unlock();}},
|
||||
new F(){void f(){rwl.writeLock().unlock();}});
|
||||
barrier.await();
|
||||
} catch (Throwable t) { unexpected(t); }}});}
|
||||
es.shutdown();
|
||||
check(es.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
|
||||
}
|
||||
|
||||
void testReentrantLocks(final boolean fair,
|
||||
final boolean serialClone) throws Throwable {
|
||||
final ReentrantLock rl = serialClone ?
|
||||
serialClone(new ReentrantLock(fair)) :
|
||||
new ReentrantLock(fair);
|
||||
final ReentrantReadWriteLock rwl = serialClone ?
|
||||
serialClone(new ReentrantReadWriteLock(fair)) :
|
||||
new ReentrantReadWriteLock(fair);
|
||||
final int depth = 10;
|
||||
equal(rl.isFair(), fair);
|
||||
equal(rwl.isFair(), fair);
|
||||
check(! rl.isLocked());
|
||||
check(! rwl.isWriteLocked());
|
||||
check(! rl.isHeldByCurrentThread());
|
||||
check(! rwl.isWriteLockedByCurrentThread());
|
||||
check(! rwl.writeLock().isHeldByCurrentThread());
|
||||
|
||||
for (int i = 0; i < depth; i++) {
|
||||
equal(rl.getHoldCount(), i);
|
||||
equal(rwl.getReadLockCount(), i);
|
||||
equal(rwl.getReadHoldCount(), i);
|
||||
equal(rwl.getWriteHoldCount(), i);
|
||||
equal(rwl.writeLock().getHoldCount(), i);
|
||||
equal(rl.isLocked(), i > 0);
|
||||
equal(rwl.isWriteLocked(), i > 0);
|
||||
lock(rl);
|
||||
lock(rwl.writeLock());
|
||||
lock(rwl.readLock());
|
||||
}
|
||||
|
||||
for (int i = depth; i > 0; i--) {
|
||||
check(! rl.hasQueuedThreads());
|
||||
check(! rwl.hasQueuedThreads());
|
||||
check(! rl.hasQueuedThread(Thread.currentThread()));
|
||||
check(! rwl.hasQueuedThread(Thread.currentThread()));
|
||||
check(rl.isLocked());
|
||||
check(rwl.isWriteLocked());
|
||||
check(rl.isHeldByCurrentThread());
|
||||
check(rwl.isWriteLockedByCurrentThread());
|
||||
check(rwl.writeLock().isHeldByCurrentThread());
|
||||
equal(rl.getQueueLength(), 0);
|
||||
equal(rwl.getQueueLength(), 0);
|
||||
equal(rwl.getReadLockCount(), i);
|
||||
equal(rl.getHoldCount(), i);
|
||||
equal(rwl.getReadHoldCount(), i);
|
||||
equal(rwl.getWriteHoldCount(), i);
|
||||
equal(rwl.writeLock().getHoldCount(), i);
|
||||
rwl.readLock().unlock();
|
||||
rwl.writeLock().unlock();
|
||||
rl.unlock();
|
||||
}
|
||||
THROWS(IllegalMonitorStateException.class,
|
||||
new F(){void f(){rl.unlock();}},
|
||||
new F(){void f(){rwl.readLock().unlock();}},
|
||||
new F(){void f(){rwl.writeLock().unlock();}});
|
||||
}
|
||||
|
||||
//--------------------- Infrastructure ---------------------------
|
||||
volatile int passed = 0, failed = 0;
|
||||
void pass() {passed++;}
|
||||
void fail() {failed++; Thread.dumpStack();}
|
||||
void fail(String msg) {System.err.println(msg); fail();}
|
||||
void unexpected(Throwable t) {failed++; t.printStackTrace();}
|
||||
void check(boolean cond) {if (cond) pass(); else fail();}
|
||||
void equal(Object x, Object y) {
|
||||
if (x == null ? y == null : x.equals(y)) pass();
|
||||
else fail(x + " not equal to " + y);}
|
||||
public static void main(String[] args) throws Throwable {
|
||||
new Count().instanceMain(args);}
|
||||
void instanceMain(String[] args) throws Throwable {
|
||||
try {test(args);} catch (Throwable t) {unexpected(t);}
|
||||
System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
|
||||
if (failed > 0) throw new AssertionError("Some tests failed");}
|
||||
abstract class F {abstract void f() throws Throwable;}
|
||||
void THROWS(Class<? extends Throwable> k, F... fs) {
|
||||
for (F f : fs)
|
||||
try {f.f(); fail("Expected " + k.getName() + " not thrown");}
|
||||
catch (Throwable t) {
|
||||
if (k.isAssignableFrom(t.getClass())) pass();
|
||||
else unexpected(t);}}
|
||||
|
||||
static byte[] serializedForm(Object obj) {
|
||||
try {
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
new ObjectOutputStream(baos).writeObject(obj);
|
||||
return baos.toByteArray();
|
||||
} catch (IOException e) { throw new RuntimeException(e); }}
|
||||
static Object readObject(byte[] bytes)
|
||||
throws IOException, ClassNotFoundException {
|
||||
InputStream is = new ByteArrayInputStream(bytes);
|
||||
return new ObjectInputStream(is).readObject();}
|
||||
@SuppressWarnings("unchecked")
|
||||
static <T> T serialClone(T obj) {
|
||||
try { return (T) readObject(serializedForm(obj)); }
|
||||
catch (Exception e) { throw new RuntimeException(e); }}
|
||||
}
|
||||
|
|
@ -0,0 +1,103 @@
|
|||
/*
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
/*
|
||||
* This file is available under and governed by the GNU General Public
|
||||
* License version 2 only, as published by the Free Software Foundation.
|
||||
* However, the following notice accompanied the original version of this
|
||||
* file:
|
||||
*
|
||||
* Written by Doug Lea with assistance from members of JCP JSR-166
|
||||
* Expert Group and released to the public domain, as explained at
|
||||
* http://creativecommons.org/publicdomain/zero/1.0/
|
||||
*/
|
||||
|
||||
/**
|
||||
* Misc utilities in JSR166 performance tests
|
||||
*/
|
||||
class LoopHelpers {
|
||||
|
||||
// Some mindless computation to do between synchronizations...
|
||||
|
||||
/**
|
||||
* generates 32 bit pseudo-random numbers.
|
||||
* Adapted from http://www.snippets.org
|
||||
*/
|
||||
public static int compute1(int x) {
|
||||
int lo = 16807 * (x & 0xFFFF);
|
||||
int hi = 16807 * (x >>> 16);
|
||||
lo += (hi & 0x7FFF) << 16;
|
||||
if ((lo & 0x80000000) != 0) {
|
||||
lo &= 0x7fffffff;
|
||||
++lo;
|
||||
}
|
||||
lo += hi >>> 15;
|
||||
if (lo == 0 || (lo & 0x80000000) != 0) {
|
||||
lo &= 0x7fffffff;
|
||||
++lo;
|
||||
}
|
||||
return lo;
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes a linear congruential random number a random number
|
||||
* of times.
|
||||
*/
|
||||
public static int compute2(int x) {
|
||||
int loops = (x >>> 4) & 7;
|
||||
while (loops-- > 0) {
|
||||
x = (x * 2147483647) % 16807;
|
||||
}
|
||||
return x;
|
||||
}
|
||||
|
||||
public static class BarrierTimer implements Runnable {
|
||||
public volatile long startTime;
|
||||
public volatile long endTime;
|
||||
public void run() {
|
||||
long t = System.nanoTime();
|
||||
if (startTime == 0)
|
||||
startTime = t;
|
||||
else
|
||||
endTime = t;
|
||||
}
|
||||
public void clear() {
|
||||
startTime = 0;
|
||||
endTime = 0;
|
||||
}
|
||||
public long getTime() {
|
||||
return endTime - startTime;
|
||||
}
|
||||
}
|
||||
|
||||
public static String rightJustify(long n) {
|
||||
// There's probably a better way to do this...
|
||||
String field = " ";
|
||||
String num = Long.toString(n);
|
||||
if (num.length() >= field.length())
|
||||
return num;
|
||||
StringBuilder b = new StringBuilder(field);
|
||||
b.replace(b.length()-num.length(), b.length(), num);
|
||||
return b.toString();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,201 @@
|
|||
/*
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
/*
|
||||
* This file is available under and governed by the GNU General Public
|
||||
* License version 2 only, as published by the Free Software Foundation.
|
||||
* However, the following notice accompanied the original version of this
|
||||
* file:
|
||||
*
|
||||
* Written by Doug Lea with assistance from members of JCP JSR-166
|
||||
* Expert Group and released to the public domain, as explained at
|
||||
* http://creativecommons.org/publicdomain/zero/1.0/
|
||||
*/
|
||||
|
||||
/*
|
||||
* @test
|
||||
* @bug 4486658
|
||||
* @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
|
||||
* table includes key. If absent, with probability pinsert it
|
||||
* inserts it, and if present, with probability premove it removes
|
||||
* it. (pinsert and premove are expressed as percentages to simplify
|
||||
* parsing from command line.)
|
||||
* @library /test/lib
|
||||
*/
|
||||
|
||||
import static java.util.concurrent.TimeUnit.MILLISECONDS;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.SplittableRandom;
|
||||
import java.util.concurrent.CyclicBarrier;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import jdk.test.lib.Utils;
|
||||
|
||||
public class MapLoops {
|
||||
static final long LONG_DELAY_MS = Utils.adjustTimeout(10_000);
|
||||
static final int NKEYS = 100000;
|
||||
static int pinsert = 60;
|
||||
static int premove = 2;
|
||||
static int maxThreads = 5;
|
||||
static int nops = 10000; // 1000000
|
||||
static int removesPerMaxRandom;
|
||||
static int insertsPerMaxRandom;
|
||||
|
||||
static final ExecutorService pool = Executors.newCachedThreadPool();
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
|
||||
Class mapClass = null;
|
||||
if (args.length > 0) {
|
||||
try {
|
||||
mapClass = Class.forName(args[0]);
|
||||
} catch (ClassNotFoundException e) {
|
||||
throw new RuntimeException("Class " + args[0] + " not found.");
|
||||
}
|
||||
}
|
||||
else
|
||||
mapClass = RWMap.class;
|
||||
|
||||
if (args.length > 1)
|
||||
maxThreads = Integer.parseInt(args[1]);
|
||||
|
||||
if (args.length > 2)
|
||||
nops = Integer.parseInt(args[2]);
|
||||
|
||||
if (args.length > 3)
|
||||
pinsert = Integer.parseInt(args[3]);
|
||||
|
||||
if (args.length > 4)
|
||||
premove = Integer.parseInt(args[4]);
|
||||
|
||||
// normalize probabilities wrt random number generator
|
||||
removesPerMaxRandom = (int)((double)premove/100.0 * 0x7FFFFFFFL);
|
||||
insertsPerMaxRandom = (int)((double)pinsert/100.0 * 0x7FFFFFFFL);
|
||||
|
||||
System.out.println("Using " + mapClass.getName());
|
||||
|
||||
SplittableRandom rnd = new SplittableRandom();
|
||||
Integer[] key = new Integer[NKEYS];
|
||||
for (int i = 0; i < key.length; ++i)
|
||||
key[i] = new Integer(rnd.nextInt());
|
||||
|
||||
// warmup
|
||||
System.out.println("Warmup...");
|
||||
for (int k = 0; k < 2; ++k) {
|
||||
Map<Integer, Integer> map = (Map<Integer, Integer>)
|
||||
mapClass.getDeclaredConstructor().newInstance();
|
||||
LoopHelpers.BarrierTimer timer = new LoopHelpers.BarrierTimer();
|
||||
CyclicBarrier barrier = new CyclicBarrier(1, timer);
|
||||
new Runner(map, key, barrier, rnd.split()).run();
|
||||
map.clear();
|
||||
}
|
||||
|
||||
for (int i = 1; i <= maxThreads; i += (i+1) >>> 1) {
|
||||
System.out.print("Threads: " + i + "\t:");
|
||||
Map<Integer, Integer> map = (Map<Integer, Integer>)
|
||||
mapClass.getDeclaredConstructor().newInstance();
|
||||
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, rnd.split()));
|
||||
barrier.await();
|
||||
barrier.await();
|
||||
long time = timer.getTime();
|
||||
long tpo = time / (i * (long)nops);
|
||||
System.out.print(LoopHelpers.rightJustify(tpo) + " ns per op");
|
||||
double secs = (double)time / 1000000000.0;
|
||||
System.out.println("\t " + secs + "s run time");
|
||||
map.clear();
|
||||
}
|
||||
pool.shutdown();
|
||||
if (! pool.awaitTermination(LONG_DELAY_MS, MILLISECONDS))
|
||||
throw new Error();
|
||||
}
|
||||
|
||||
static class Runner implements Runnable {
|
||||
final Map<Integer,Integer> map;
|
||||
final Integer[] key;
|
||||
final CyclicBarrier barrier;
|
||||
final SplittableRandom rnd;
|
||||
int position;
|
||||
int total;
|
||||
|
||||
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 = rnd.nextInt(Integer.MAX_VALUE);
|
||||
position += (r & 7) - 3;
|
||||
while (position >= key.length) position -= key.length;
|
||||
while (position < 0) position += key.length;
|
||||
|
||||
Integer k = key[position];
|
||||
Integer x = map.get(k);
|
||||
|
||||
if (x != null) {
|
||||
if (x.intValue() != k.intValue())
|
||||
throw new Error("bad mapping: " + x + " to " + k);
|
||||
|
||||
if (r < removesPerMaxRandom) {
|
||||
// get away from this position
|
||||
position = r % key.length;
|
||||
map.remove(k);
|
||||
return 2;
|
||||
}
|
||||
else
|
||||
total += LoopHelpers.compute2(LoopHelpers.compute1(x.intValue()));
|
||||
}
|
||||
else {
|
||||
if (r < insertsPerMaxRandom) {
|
||||
map.put(k, k);
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
public void run() {
|
||||
try {
|
||||
barrier.await();
|
||||
int ops = nops;
|
||||
while (ops > 0)
|
||||
ops -= step();
|
||||
barrier.await();
|
||||
}
|
||||
catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,143 @@
|
|||
/*
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
/*
|
||||
* This file is available under and governed by the GNU General Public
|
||||
* License version 2 only, as published by the Free Software Foundation.
|
||||
* However, the following notice accompanied the original version of this
|
||||
* file:
|
||||
*
|
||||
* Written by Doug Lea with assistance from members of JCP JSR-166
|
||||
* Expert Group and released to the public domain, as explained at
|
||||
* http://creativecommons.org/publicdomain/zero/1.0/
|
||||
*/
|
||||
|
||||
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
|
||||
* that places read-write locks around unsynchronized Maps.
|
||||
* Exists as a sample input for MapLoops test.
|
||||
*/
|
||||
public class RWMap implements Map {
|
||||
private final Map m;
|
||||
private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
|
||||
|
||||
public RWMap(Map m) {
|
||||
if (m == null)
|
||||
throw new NullPointerException();
|
||||
this.m = m;
|
||||
}
|
||||
|
||||
public RWMap() {
|
||||
this(new TreeMap()); // use TreeMap by default
|
||||
}
|
||||
|
||||
public int size() {
|
||||
rwl.readLock().lock();
|
||||
try { return m.size(); }
|
||||
finally { rwl.readLock().unlock(); }
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
rwl.readLock().lock();
|
||||
try { return m.isEmpty(); }
|
||||
finally { rwl.readLock().unlock(); }
|
||||
}
|
||||
|
||||
public Object get(Object key) {
|
||||
rwl.readLock().lock();
|
||||
try { return m.get(key); }
|
||||
finally { rwl.readLock().unlock(); }
|
||||
}
|
||||
|
||||
public boolean containsKey(Object key) {
|
||||
rwl.readLock().lock();
|
||||
try { return m.containsKey(key); }
|
||||
finally { rwl.readLock().unlock(); }
|
||||
}
|
||||
|
||||
public boolean containsValue(Object value) {
|
||||
rwl.readLock().lock();
|
||||
try { return m.containsValue(value); }
|
||||
finally { rwl.readLock().unlock(); }
|
||||
}
|
||||
|
||||
public Set keySet() { // Not implemented
|
||||
return null;
|
||||
}
|
||||
|
||||
public Set entrySet() { // Not implemented
|
||||
return null;
|
||||
}
|
||||
|
||||
public Collection values() { // Not implemented
|
||||
return null;
|
||||
}
|
||||
|
||||
public boolean equals(Object o) {
|
||||
rwl.readLock().lock();
|
||||
try { return m.equals(o); }
|
||||
finally { rwl.readLock().unlock(); }
|
||||
}
|
||||
|
||||
public int hashCode() {
|
||||
rwl.readLock().lock();
|
||||
try { return m.hashCode(); }
|
||||
finally { rwl.readLock().unlock(); }
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
rwl.readLock().lock();
|
||||
try { return m.toString(); }
|
||||
finally { rwl.readLock().unlock(); }
|
||||
}
|
||||
|
||||
public Object put(Object key, Object value) {
|
||||
rwl.writeLock().lock();
|
||||
try { return m.put(key, value); }
|
||||
finally { rwl.writeLock().unlock(); }
|
||||
}
|
||||
|
||||
public Object remove(Object key) {
|
||||
rwl.writeLock().lock();
|
||||
try { return m.remove(key); }
|
||||
finally { rwl.writeLock().unlock(); }
|
||||
}
|
||||
|
||||
public void putAll(Map map) {
|
||||
rwl.writeLock().lock();
|
||||
try { m.putAll(map); }
|
||||
finally { rwl.writeLock().unlock(); }
|
||||
}
|
||||
|
||||
public void clear() {
|
||||
rwl.writeLock().lock();
|
||||
try { m.clear(); }
|
||||
finally { rwl.writeLock().unlock(); }
|
||||
}
|
||||
|
||||
}
|
||||
673
test/jdk/java/util/concurrent/locks/StampedLock/Basic.java
Normal file
673
test/jdk/java/util/concurrent/locks/StampedLock/Basic.java
Normal file
|
|
@ -0,0 +1,673 @@
|
|||
/*
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
/*
|
||||
* This file is available under and governed by the GNU General Public
|
||||
* License version 2 only, as published by the Free Software Foundation.
|
||||
* However, the following notice accompanied the original version of this
|
||||
* file:
|
||||
*
|
||||
* Written by Doug Lea with assistance from members of JCP JSR-166
|
||||
* Expert Group and released to the public domain, as explained at
|
||||
* http://creativecommons.org/publicdomain/zero/1.0/
|
||||
*/
|
||||
|
||||
/*
|
||||
* @test
|
||||
* @bug 8005697
|
||||
* @summary Basic tests for StampedLock
|
||||
* @library /test/lib
|
||||
* @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 java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.locks.Lock;
|
||||
import java.util.concurrent.locks.ReadWriteLock;
|
||||
import java.util.concurrent.locks.StampedLock;
|
||||
import jdk.test.lib.Utils;
|
||||
|
||||
public class Basic {
|
||||
static final long LONG_DELAY_MS = Utils.adjustTimeout(10_000);
|
||||
|
||||
static void checkResult(Locker l, Class<? extends Throwable> c) {
|
||||
Throwable t = l.thrown();
|
||||
if (! ((t == null && c == null) || (c != null && c.isInstance(t)))) {
|
||||
fail("Mismatch in thread " +
|
||||
l.getName() + ": " +
|
||||
t + ", " +
|
||||
(c == null ? "<null>" : c.getName()));
|
||||
}
|
||||
|
||||
if (c == null)
|
||||
check(l.stamp() != 0L); // must have acquired the lock
|
||||
else
|
||||
check(l.stamp() == 0L); // must NOT have acquired the lock
|
||||
}
|
||||
|
||||
//----------------------------------------------------------------
|
||||
// Mechanism to get all test threads into "running" mode.
|
||||
//----------------------------------------------------------------
|
||||
static void toTheStartingGate(Phaser gate) {
|
||||
try {
|
||||
gate.arriveAndAwaitAdvance();
|
||||
} catch (Throwable t) {
|
||||
unexpected(t);
|
||||
}
|
||||
}
|
||||
|
||||
abstract static class Locker extends Thread {
|
||||
static AtomicInteger count = new AtomicInteger(1);
|
||||
private volatile Throwable thrown;
|
||||
private volatile long stamp;
|
||||
protected void thrown(Throwable thrown) { this.thrown = thrown; }
|
||||
public Throwable thrown() { return thrown; }
|
||||
protected void stamp(long stamp) { this.stamp = stamp; }
|
||||
public long stamp() { return stamp; }
|
||||
|
||||
Locker() {
|
||||
this("Locker");
|
||||
}
|
||||
|
||||
Locker(String name) {
|
||||
this.setName(name + ":" + count.getAndIncrement());
|
||||
this.setDaemon(true);
|
||||
}
|
||||
}
|
||||
|
||||
abstract static class Reader extends Locker {
|
||||
Reader() { super("Reader"); }
|
||||
Reader(String name) { super(name); }
|
||||
}
|
||||
|
||||
static Reader reader(final StampedLock sl, final Phaser gate) {
|
||||
return new Reader() { public void run() {
|
||||
if (gate != null ) toTheStartingGate(gate);
|
||||
stamp(sl.readLock());
|
||||
try {
|
||||
check(sl.validate(stamp()));
|
||||
check(sl.isReadLocked());
|
||||
check(!sl.isWriteLocked());
|
||||
} finally { sl.unlockRead(stamp()); } }};
|
||||
}
|
||||
|
||||
static Reader readerView(final StampedLock sl, final Phaser gate) {
|
||||
return new Reader("ReaderView") { public void run() {
|
||||
if (gate != null ) toTheStartingGate(gate);
|
||||
final Lock rl = sl.asReadLock();
|
||||
rl.lock();
|
||||
try {
|
||||
stamp(1L); // got the lock
|
||||
check(sl.isReadLocked());
|
||||
check(!sl.isWriteLocked());
|
||||
} finally { rl.unlock(); } }};
|
||||
}
|
||||
|
||||
static Reader reader(StampedLock sl, Phaser gate, boolean view) {
|
||||
return view ? readerView(sl, gate) : reader(sl, gate);
|
||||
}
|
||||
|
||||
static Reader interruptibleReader(final StampedLock sl,
|
||||
final long timeout,
|
||||
final TimeUnit unit,
|
||||
final Phaser gate) {
|
||||
return new Reader("InterruptibleReader") { public void run() {
|
||||
if (gate != null ) toTheStartingGate(gate);
|
||||
try {
|
||||
if (timeout < 0)
|
||||
stamp(sl.readLockInterruptibly());
|
||||
else
|
||||
stamp(sl.tryReadLock(timeout, unit));
|
||||
check(sl.validate(stamp()));
|
||||
check(sl.isReadLocked());
|
||||
check(!sl.isWriteLocked());
|
||||
} catch (Throwable x) { thrown(x);
|
||||
} finally { if (stamp() != 0L) sl.unlockRead(stamp()); } }};
|
||||
}
|
||||
|
||||
static Reader interruptibleReaderView(final StampedLock sl,
|
||||
final long timeout,
|
||||
final TimeUnit unit,
|
||||
final Phaser gate) {
|
||||
return new Reader("InterruptibleReaderView") { public void run() {
|
||||
if (gate != null ) toTheStartingGate(gate);
|
||||
final Lock rl = sl.asReadLock();
|
||||
|
||||
try {
|
||||
if (timeout < 0)
|
||||
rl.lockInterruptibly();
|
||||
else
|
||||
rl.tryLock(timeout, unit);
|
||||
stamp(1L); // got the lock
|
||||
check(sl.isReadLocked());
|
||||
check(!sl.isWriteLocked());
|
||||
} catch (Throwable x) { thrown(x);
|
||||
} finally { if (stamp() != 0L) rl.unlock(); } }};
|
||||
}
|
||||
|
||||
static Reader interruptibleReader(final StampedLock sl,
|
||||
final long timeout,
|
||||
final TimeUnit unit,
|
||||
final Phaser gate,
|
||||
final boolean view) {
|
||||
return view ? interruptibleReaderView(sl, timeout, unit, gate)
|
||||
: interruptibleReader(sl, timeout, unit, gate);
|
||||
}
|
||||
|
||||
abstract static class Writer extends Locker {
|
||||
Writer() { super("Writer"); }
|
||||
Writer(String name) { super(name); }
|
||||
}
|
||||
|
||||
static Writer writer(final StampedLock sl, final Phaser gate) {
|
||||
return new Writer() { public void run() {
|
||||
if (gate != null ) toTheStartingGate(gate);
|
||||
try {
|
||||
stamp(sl.writeLock());
|
||||
check(sl.validate(stamp()));
|
||||
check(!sl.isReadLocked());
|
||||
check(sl.isWriteLocked());
|
||||
} finally { sl.unlockWrite(stamp()); } }};
|
||||
}
|
||||
|
||||
static Writer writerView(final StampedLock sl, final Phaser gate) {
|
||||
return new Writer("WriterView") { public void run() {
|
||||
if (gate != null ) toTheStartingGate(gate);
|
||||
Lock wl = sl.asWriteLock();
|
||||
wl.lock();
|
||||
try {
|
||||
stamp(1L); // got the lock
|
||||
check(!sl.isReadLocked());
|
||||
check(sl.isWriteLocked());
|
||||
} finally { wl.unlock(); } }};
|
||||
}
|
||||
|
||||
static Writer writer(StampedLock sl, Phaser gate, boolean view) {
|
||||
return view ? writerView(sl, gate) : writer(sl, gate);
|
||||
}
|
||||
|
||||
static Writer interruptibleWriter(final StampedLock sl,
|
||||
final long timeout,
|
||||
final TimeUnit unit,
|
||||
final Phaser gate) {
|
||||
return new Writer("InterruptibleWriter") { public void run() {
|
||||
if (gate != null ) toTheStartingGate(gate);
|
||||
try {
|
||||
if (timeout < 0)
|
||||
stamp(sl.writeLockInterruptibly());
|
||||
else
|
||||
stamp(sl.tryWriteLock(timeout, unit));
|
||||
check(sl.validate(stamp()));
|
||||
check(!sl.isReadLocked());
|
||||
check(sl.isWriteLocked());
|
||||
} catch (Throwable x) { thrown(x);
|
||||
} finally { if (stamp() != 0L) sl.unlockWrite(stamp()); } }};
|
||||
}
|
||||
|
||||
static Writer interruptibleWriterView(final StampedLock sl,
|
||||
final long timeout,
|
||||
final TimeUnit unit,
|
||||
final Phaser gate) {
|
||||
return new Writer("InterruptibleWriterView") { public void run() {
|
||||
if (gate != null ) toTheStartingGate(gate);
|
||||
Lock wl = sl.asWriteLock();
|
||||
try {
|
||||
if (timeout < 0)
|
||||
wl.lockInterruptibly();
|
||||
else
|
||||
wl.tryLock(timeout, unit);
|
||||
stamp(1L); // got the lock
|
||||
check(!sl.isReadLocked());
|
||||
check(sl.isWriteLocked());
|
||||
} catch (Throwable x) { thrown(x);
|
||||
} finally { if (stamp() != 0L) wl.unlock(); } }};
|
||||
}
|
||||
|
||||
static Writer interruptibleWriter(final StampedLock sl,
|
||||
final long timeout,
|
||||
final TimeUnit unit,
|
||||
final Phaser gate,
|
||||
final boolean view) {
|
||||
return view ? interruptibleWriterView(sl, timeout, unit, gate)
|
||||
: interruptibleWriter(sl, timeout, unit, gate);
|
||||
}
|
||||
|
||||
// Returns an infinite lazy list of all possible reader combinations.
|
||||
static Iterator<Reader> readerIterator(final StampedLock sl,
|
||||
final Phaser gate) {
|
||||
return new Iterator<Reader>() {
|
||||
int i = 0;
|
||||
boolean view = false;
|
||||
public boolean hasNext() { return true; }
|
||||
public Reader next() {
|
||||
switch ((i++)&7) {
|
||||
case 1: case 4: case 7:
|
||||
return reader(sl, gate, view ^= true);
|
||||
case 2: case 5:
|
||||
return interruptibleReader(sl, -1, SECONDS, gate, view ^= true);
|
||||
default:
|
||||
return interruptibleReader(sl, LONG_DELAY_MS, MILLISECONDS, gate, view ^= true); }}
|
||||
public void remove() {throw new UnsupportedOperationException();}};
|
||||
}
|
||||
|
||||
// Returns an infinite lazy list of all possible writer combinations.
|
||||
static Iterator<Writer> writerIterator(final StampedLock sl,
|
||||
final Phaser gate) {
|
||||
return new Iterator<Writer>() {
|
||||
int i = 0;
|
||||
boolean view = false;
|
||||
public boolean hasNext() { return true; }
|
||||
public Writer next() {
|
||||
switch ((i++)&7) {
|
||||
case 1: case 4: case 7:
|
||||
return writer(sl, gate, view ^= true);
|
||||
case 2: case 5:
|
||||
return interruptibleWriter(sl, -1, SECONDS, gate, view ^= true);
|
||||
default:
|
||||
return interruptibleWriter(sl, LONG_DELAY_MS, MILLISECONDS, gate, view ^= true); }}
|
||||
public void remove() {throw new UnsupportedOperationException();}};
|
||||
}
|
||||
|
||||
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"); }
|
||||
}
|
||||
|
||||
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();
|
||||
|
||||
//----------------------------------------------------------------
|
||||
System.out.print("Some basic sanity: ");
|
||||
//----------------------------------------------------------------
|
||||
try {
|
||||
final StampedLock sl = new StampedLock();
|
||||
check(!sl.isReadLocked());
|
||||
check(!sl.isWriteLocked());
|
||||
long stamp = sl.tryOptimisticRead();
|
||||
check(stamp != 0L);
|
||||
check(sl.validate(stamp));
|
||||
check(!sl.validate(0));
|
||||
|
||||
stamp = sl.writeLock();
|
||||
try {
|
||||
check(sl.validate(stamp));
|
||||
check(!sl.isReadLocked());
|
||||
check(sl.isWriteLocked());
|
||||
check(sl.tryReadLock() == 0L);
|
||||
check(sl.tryReadLock(1, MILLISECONDS) == 0L);
|
||||
check(sl.tryOptimisticRead() == 0L);
|
||||
check(sl.tryWriteLock() == 0L);
|
||||
check(sl.tryWriteLock(1, MILLISECONDS) == 0L);
|
||||
check(!sl.tryUnlockRead());
|
||||
check(sl.tryConvertToWriteLock(stamp) == stamp);
|
||||
try {
|
||||
sl.unlockRead(stamp);
|
||||
fail("Expected unlockRead to throw when not holding read lock");
|
||||
} catch (IllegalMonitorStateException x) {
|
||||
pass();
|
||||
}
|
||||
check(sl.validate(stamp));
|
||||
} finally {
|
||||
sl.unlockWrite(stamp);
|
||||
}
|
||||
check(!sl.isWriteLocked());
|
||||
|
||||
stamp = sl.readLock();
|
||||
try {
|
||||
check(sl.validate(stamp));
|
||||
check(sl.isReadLocked());
|
||||
check(!sl.isWriteLocked());
|
||||
check(sl.tryOptimisticRead() != 0L);
|
||||
check(sl.tryWriteLock() == 0L);
|
||||
check(sl.tryWriteLock(1, MILLISECONDS) == 0L);
|
||||
check(!sl.tryUnlockWrite());
|
||||
check(sl.tryConvertToReadLock(stamp) == stamp);
|
||||
try {
|
||||
sl.unlockWrite(stamp);
|
||||
fail("Expected unlockWrite to throw when not holding read lock");
|
||||
} catch (IllegalMonitorStateException x) {
|
||||
pass();
|
||||
}
|
||||
check(sl.validate(stamp));
|
||||
} finally {
|
||||
sl.unlockRead(stamp);
|
||||
}
|
||||
check(!sl.isReadLocked());
|
||||
|
||||
stamp = sl.tryReadLock(1, MILLISECONDS);
|
||||
try {
|
||||
check(stamp != 0L);
|
||||
} finally {
|
||||
sl.unlockRead(stamp);
|
||||
}
|
||||
} catch (Throwable t) { unexpected(t); }
|
||||
timer.printElapsed();
|
||||
|
||||
//----------------------------------------------------------------
|
||||
System.out.print("Multiple writers single reader: ");
|
||||
//----------------------------------------------------------------
|
||||
try {
|
||||
StampedLock sl = new StampedLock();
|
||||
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 < 2; i++) {
|
||||
check(!sl.isReadLocked());
|
||||
check(!sl.isWriteLocked());
|
||||
check(!sl.tryUnlockRead());
|
||||
check(!sl.tryUnlockWrite());
|
||||
check(sl.tryOptimisticRead() != 0L);
|
||||
Locker[] wThreads = new Locker[nThreads];
|
||||
for (int j=0; j<nThreads; j++)
|
||||
wThreads[j] = writers.next();
|
||||
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<nThreads; j++)
|
||||
wThreads[j].join();
|
||||
for (int j=0; j<nThreads; j++)
|
||||
checkResult(wThreads[j], null);
|
||||
checkResult(reader, null);
|
||||
}
|
||||
} catch (Throwable t) { unexpected(t); }
|
||||
timer.printElapsed();
|
||||
|
||||
//----------------------------------------------------------------
|
||||
System.out.print("Multiple readers single writer: ");
|
||||
//----------------------------------------------------------------
|
||||
try {
|
||||
StampedLock sl = new StampedLock();
|
||||
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 < 2; i++) {
|
||||
check(!sl.isReadLocked());
|
||||
check(!sl.isWriteLocked());
|
||||
check(!sl.tryUnlockRead());
|
||||
check(!sl.tryUnlockWrite());
|
||||
check(sl.tryOptimisticRead() != 0L);
|
||||
Locker[] rThreads = new Locker[nThreads];
|
||||
for (int j=0; j<nThreads; j++)
|
||||
rThreads[j] = readers.next();
|
||||
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<nThreads; j++)
|
||||
rThreads[j].join();
|
||||
for (int j=0; j<nThreads; j++)
|
||||
checkResult(rThreads[j], null);
|
||||
checkResult(writer, null);
|
||||
}
|
||||
} catch (Throwable t) { unexpected(t); }
|
||||
timer.printElapsed();
|
||||
|
||||
//----------------------------------------------------------------
|
||||
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, LONG_DELAY_MS, -1L, LONG_DELAY_MS }) {
|
||||
long stamp;
|
||||
Thread.State state;
|
||||
|
||||
stamp = sl.writeLock();
|
||||
try {
|
||||
Reader r = interruptibleReader(sl, timeout, MILLISECONDS, null, view);
|
||||
r.start();
|
||||
r.interrupt();
|
||||
r.join();
|
||||
checkResult(r, InterruptedException.class);
|
||||
} finally {
|
||||
sl.unlockWrite(stamp);
|
||||
}
|
||||
|
||||
stamp = sl.writeLock();
|
||||
try {
|
||||
Reader r = interruptibleReader(sl, timeout, MILLISECONDS, 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, MILLISECONDS, null, view);
|
||||
w.start();
|
||||
w.interrupt();
|
||||
w.join();
|
||||
checkResult(w, InterruptedException.class);
|
||||
} finally {
|
||||
sl.unlockRead(stamp);
|
||||
}
|
||||
|
||||
stamp = sl.readLock();
|
||||
try {
|
||||
Writer w = interruptibleWriter(sl, timeout, MILLISECONDS, 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());
|
||||
check(!sl.tryUnlockWrite());
|
||||
check(sl.tryOptimisticRead() != 0L);
|
||||
if (timeout == LONG_DELAY_MS)
|
||||
view = true;
|
||||
}
|
||||
} catch (Throwable t) { unexpected(t); }
|
||||
timer.printElapsed();
|
||||
|
||||
//----------------------------------------------------------------
|
||||
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, MILLISECONDS) == 0L);
|
||||
} finally {
|
||||
sl.unlockWrite(stamp);
|
||||
}
|
||||
stamp = sl.readLock();
|
||||
try {
|
||||
check(sl.tryWriteLock(timeout, MILLISECONDS) == 0L);
|
||||
} finally {
|
||||
sl.unlockRead(stamp);
|
||||
}
|
||||
check(!sl.isReadLocked());
|
||||
check(!sl.isWriteLocked());
|
||||
check(!sl.tryUnlockRead());
|
||||
check(!sl.tryUnlockWrite());
|
||||
check(sl.tryOptimisticRead() != 0L);
|
||||
}
|
||||
} catch (Throwable t) { unexpected(t); }
|
||||
timer.printElapsed();
|
||||
|
||||
//----------------------------------------------------------------
|
||||
System.out.print("optimistic read: ");
|
||||
//----------------------------------------------------------------
|
||||
try {
|
||||
StampedLock sl = new StampedLock();
|
||||
Iterator<Writer> writers = writerIterator(sl, null);
|
||||
Iterator<Reader> readers = readerIterator(sl, null);
|
||||
for (int i = 0; i < 10; i++) {
|
||||
check(!sl.isReadLocked());
|
||||
check(!sl.isWriteLocked());
|
||||
check(!sl.tryUnlockRead());
|
||||
check(!sl.tryUnlockWrite());
|
||||
long stamp = sl.tryOptimisticRead();
|
||||
check(stamp != 0L);
|
||||
check(sl.tryConvertToOptimisticRead(stamp) == stamp);
|
||||
Reader r = readers.next(); r.start();
|
||||
r.join();
|
||||
checkResult(r, null);
|
||||
check(sl.validate(stamp));
|
||||
check(sl.tryConvertToOptimisticRead(stamp) == stamp);
|
||||
Writer w = writers.next(); w.start();
|
||||
w.join();
|
||||
checkResult(w, null);
|
||||
check(sl.validate(stamp) == false);
|
||||
}
|
||||
} catch (Throwable t) { unexpected(t); }
|
||||
timer.printElapsed();
|
||||
|
||||
//----------------------------------------------------------------
|
||||
System.out.print("convert: ");
|
||||
//----------------------------------------------------------------
|
||||
try {
|
||||
StampedLock sl = new StampedLock();
|
||||
for (int i = 0; i < 2; i++) {
|
||||
check(!sl.isReadLocked());
|
||||
check(!sl.isWriteLocked());
|
||||
check(!sl.tryUnlockRead());
|
||||
check(!sl.tryUnlockWrite());
|
||||
long stamp = sl.tryOptimisticRead();
|
||||
check(stamp != 0L);
|
||||
check((stamp = sl.tryConvertToReadLock(stamp)) != 0L);
|
||||
check(sl.validate(stamp));
|
||||
check(sl.isReadLocked());
|
||||
check(sl.tryWriteLock() == 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, MILLISECONDS) == 0L);
|
||||
if (i != 0) {
|
||||
sl.unlockWrite(stamp);
|
||||
continue;
|
||||
}
|
||||
// convert down
|
||||
check((stamp = sl.tryConvertToReadLock(stamp)) != 0L);
|
||||
check(sl.validate(stamp));
|
||||
check(sl.isReadLocked());
|
||||
check(!sl.isWriteLocked());
|
||||
check(sl.tryWriteLock() == 0L);
|
||||
check(sl.tryWriteLock(1L, MILLISECONDS) == 0L);
|
||||
check((stamp = sl.tryConvertToOptimisticRead(stamp)) != 0L);
|
||||
check(sl.validate(stamp));
|
||||
check(!sl.isReadLocked());
|
||||
check(!sl.isWriteLocked());
|
||||
check(sl.validate(stamp));
|
||||
}
|
||||
} catch (Throwable t) { unexpected(t); }
|
||||
timer.printElapsed();
|
||||
|
||||
//----------------------------------------------------------------
|
||||
System.out.print("views: ");
|
||||
//----------------------------------------------------------------
|
||||
try {
|
||||
StampedLock sl = new StampedLock();
|
||||
|
||||
Lock rl = sl.asReadLock();
|
||||
Lock wl = sl.asWriteLock();
|
||||
for (int i = 0; i < 2; i++) {
|
||||
rl.lock();
|
||||
try {
|
||||
check(sl.isReadLocked());
|
||||
check(!sl.isWriteLocked());
|
||||
check(sl.tryWriteLock() == 0L);
|
||||
check(sl.tryWriteLock(1L, MILLISECONDS) == 0L);
|
||||
} finally {
|
||||
rl.unlock();
|
||||
}
|
||||
check(!sl.isReadLocked());
|
||||
check(!sl.isWriteLocked());
|
||||
|
||||
wl.lock();
|
||||
try {
|
||||
check(!sl.isReadLocked());
|
||||
check(sl.isWriteLocked());
|
||||
check(sl.tryWriteLock() == 0L);
|
||||
check(sl.tryWriteLock(1L, MILLISECONDS) == 0L);
|
||||
} finally {
|
||||
wl.unlock();
|
||||
}
|
||||
check(!sl.isReadLocked());
|
||||
check(!sl.isWriteLocked());
|
||||
|
||||
ReadWriteLock rwl = sl.asReadWriteLock();
|
||||
rl = rwl.readLock();
|
||||
wl = rwl.writeLock();
|
||||
}
|
||||
} catch (Throwable t) { unexpected(t); }
|
||||
timer.printElapsed();
|
||||
}
|
||||
|
||||
//--------------------- Infrastructure ---------------------------
|
||||
static volatile int passed = 0, failed = 0;
|
||||
static void pass() {passed++;}
|
||||
static void fail() {failed++; Thread.dumpStack();}
|
||||
static void fail(String msg) {System.out.println(msg); fail();}
|
||||
static void unexpected(Throwable t) {failed++; t.printStackTrace();}
|
||||
static void check(boolean cond) {if (cond) pass(); else fail();}
|
||||
static void equal(Object x, Object y) {
|
||||
if (x == null ? y == null : x.equals(y)) pass();
|
||||
else fail(x + " not equal to " + y);}
|
||||
public static void main(String[] args) throws Throwable {
|
||||
try {realMain(args);} catch (Throwable t) {unexpected(t);}
|
||||
System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
|
||||
if (failed > 0) throw new AssertionError("Some tests failed");}
|
||||
}
|
||||
|
|
@ -0,0 +1,143 @@
|
|||
/*
|
||||
* Copyright (c) 2013, 2025, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.Phaser;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.concurrent.locks.Condition;
|
||||
import java.util.concurrent.locks.Lock;
|
||||
import java.util.concurrent.locks.StampedLock;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* @test
|
||||
* @bug 8066859
|
||||
* @summary An adaptation of OOMEInAQS test for StampedLocks
|
||||
* @requires vm.gc.G1
|
||||
* @requires !(vm.graal.enabled & vm.compMode == "Xcomp")
|
||||
* @run main/othervm -XX:+UseG1GC -XX:-UseGCOverheadLimit -Xmx48M -XX:-UseTLAB OOMEInStampedLock
|
||||
*/
|
||||
|
||||
public class OOMEInStampedLock extends Thread {
|
||||
static final int NTHREADS = 3;
|
||||
static final int NREPS = 100;
|
||||
// statically allocate
|
||||
static final StampedLock stampedLock = new StampedLock();
|
||||
static final Lock wLock = stampedLock.asWriteLock();
|
||||
static final Lock rLock = stampedLock.asReadLock();
|
||||
static final CountDownLatch started = new CountDownLatch(1);
|
||||
static final CountDownLatch filled = new CountDownLatch(1);
|
||||
static final CountDownLatch canFill = new CountDownLatch(NTHREADS);
|
||||
static volatile Object data;
|
||||
static volatile Throwable exception;
|
||||
static int turn;
|
||||
|
||||
/**
|
||||
* For each of NTHREADS threads, REPS times: Take turns
|
||||
* executing. Introduce OOM using fillHeap during runs. In
|
||||
* addition to testing AQS, the CountDownLatches ensure that
|
||||
* methods execute at least once before OutOfMemory occurs, to
|
||||
* avoid uncontrollable impact of OOME during class-loading.
|
||||
*/
|
||||
public static void main(String[] args) throws Throwable {
|
||||
OOMEInStampedLock[] threads = new OOMEInStampedLock[NTHREADS];
|
||||
for (int i = 0; i < NTHREADS; ++i)
|
||||
(threads[i] = new OOMEInStampedLock(i)).start();
|
||||
started.countDown();
|
||||
canFill.await();
|
||||
long t0 = System.nanoTime();
|
||||
data = fillHeap();
|
||||
filled.countDown();
|
||||
long t1 = System.nanoTime();
|
||||
for (int i = 0; i < NTHREADS; ++i)
|
||||
threads[i].join();
|
||||
data = null; // free heap before reporting and terminating
|
||||
System.gc();
|
||||
Throwable ex = exception;
|
||||
if (ex != null)
|
||||
throw ex;
|
||||
System.out.println(
|
||||
"fillHeap time: " + (t1 - t0) / 1000_000 +
|
||||
" millis, whole test time: " + (System.nanoTime() - t0) / 1000_000 +
|
||||
" millis"
|
||||
);
|
||||
}
|
||||
|
||||
final int tid;
|
||||
OOMEInStampedLock(int tid) {
|
||||
this.tid = tid;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
int id = tid, nextId = (id + 1) % NTHREADS;
|
||||
final Lock wl = wLock, rl = rLock;
|
||||
try {
|
||||
started.await();
|
||||
for (int i = 0; i < NREPS; i++) {
|
||||
int t;
|
||||
rl.lock(); t = turn; rl.unlock();
|
||||
wl.lock();
|
||||
try {
|
||||
if (turn == t && turn == id)
|
||||
turn = nextId;
|
||||
} finally {
|
||||
wl.unlock();
|
||||
}
|
||||
if (i == 2) { // Subsequent AQS methods encounter OOME
|
||||
canFill.countDown();
|
||||
filled.await();
|
||||
}
|
||||
}
|
||||
data = null;
|
||||
System.gc(); // avoid getting stuck while exiting
|
||||
} catch (Throwable ex) {
|
||||
data = null;
|
||||
System.gc(); // avoid nested OOME
|
||||
exception = ex;
|
||||
}
|
||||
}
|
||||
|
||||
static Object[] fillHeap() {
|
||||
Object[] first = null, last = null;
|
||||
int size = 1 << 20;
|
||||
while (size > 0) {
|
||||
try {
|
||||
Object[] array = new Object[size];
|
||||
if (first == null) {
|
||||
first = array;
|
||||
} else {
|
||||
last[0] = array;
|
||||
}
|
||||
last = array;
|
||||
} catch (OutOfMemoryError oome) {
|
||||
size = size >>> 1;
|
||||
}
|
||||
}
|
||||
return first;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,99 @@
|
|||
/*
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
/*
|
||||
* @test
|
||||
* @bug 8023234
|
||||
* @summary StampedLock serializes readers on writer unlock
|
||||
* @author Dmitry Chyuko
|
||||
* @author Aleksey Shipilev
|
||||
*/
|
||||
|
||||
import java.util.concurrent.CyclicBarrier;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.concurrent.locks.StampedLock;
|
||||
|
||||
public class ReadersUnlockAfterWriteUnlock {
|
||||
public static void main(String[] args) throws InterruptedException {
|
||||
final int RNUM = 2;
|
||||
final int REPS = 128;
|
||||
final StampedLock sl = new StampedLock();
|
||||
final AtomicReference<Throwable> bad = new AtomicReference<>();
|
||||
|
||||
final CyclicBarrier iterationStart = new CyclicBarrier(RNUM + 1);
|
||||
final CyclicBarrier readersHaveLocks = new CyclicBarrier(RNUM);
|
||||
final CyclicBarrier writerHasLock = new CyclicBarrier(RNUM + 1);
|
||||
|
||||
Runnable reader = () -> {
|
||||
try {
|
||||
for (int i = 0; i < REPS; i++) {
|
||||
iterationStart.await();
|
||||
writerHasLock.await();
|
||||
long rs = sl.readLock();
|
||||
|
||||
// single reader blocks here indefinitely if readers
|
||||
// are serialized
|
||||
readersHaveLocks.await();
|
||||
|
||||
sl.unlockRead(rs);
|
||||
}
|
||||
} catch (Throwable ex) {
|
||||
ex.printStackTrace();
|
||||
bad.set(ex);
|
||||
}
|
||||
};
|
||||
|
||||
Thread[] threads = new Thread[RNUM];
|
||||
for (int i = 0 ; i < RNUM; i++) {
|
||||
Thread thread = new Thread(reader, "Reader");
|
||||
threads[i] = thread;
|
||||
thread.start();
|
||||
}
|
||||
for (int i = 0; i < REPS; i++) {
|
||||
try {
|
||||
iterationStart.await();
|
||||
long ws = sl.writeLock();
|
||||
writerHasLock.await();
|
||||
awaitWaitState(threads);
|
||||
sl.unlockWrite(ws);
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
}
|
||||
for (Thread thread : threads)
|
||||
thread.join();
|
||||
if (bad.get() != null)
|
||||
throw new AssertionError(bad.get());
|
||||
}
|
||||
|
||||
static void awaitWaitState(Thread[] threads) {
|
||||
restart: for (;;) {
|
||||
for (Thread thread : threads) {
|
||||
if (thread.getState() != Thread.State.WAITING) {
|
||||
Thread.yield();
|
||||
continue restart;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue