2014-01-03 16:36:27 +00:00
|
|
|
import java.util.concurrent.atomic.AtomicInteger;
|
|
|
|
import java.util.concurrent.atomic.AtomicReference;
|
|
|
|
|
|
|
|
public class AtomicReferenceConcurrentTest {
|
|
|
|
private static void runTest(final int threadCount,
|
|
|
|
final int iterationsPerThread) {
|
|
|
|
// we assume a 1ms delay per thread to try to get them all to start at the same time
|
2014-01-03 17:08:36 +00:00
|
|
|
final long startTime = System.currentTimeMillis() + threadCount + 10;
|
2014-01-03 16:36:27 +00:00
|
|
|
final AtomicReference<Integer> result = new AtomicReference<Integer>(0);
|
|
|
|
final AtomicInteger threadDoneCount = new AtomicInteger(0);
|
|
|
|
|
|
|
|
for (int i = 0; i < threadCount; i++) {
|
|
|
|
new Thread(new Runnable() {
|
|
|
|
@Override
|
|
|
|
public void run() {
|
|
|
|
try {
|
|
|
|
doOperation();
|
2014-01-03 17:08:36 +00:00
|
|
|
waitTillReady();
|
2014-01-03 16:36:27 +00:00
|
|
|
} finally {
|
|
|
|
synchronized (threadDoneCount) {
|
|
|
|
threadDoneCount.incrementAndGet();
|
|
|
|
|
|
|
|
threadDoneCount.notifyAll();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-01-03 17:08:36 +00:00
|
|
|
private void waitTillReady() {
|
2014-01-03 16:36:27 +00:00
|
|
|
long sleepTime = System.currentTimeMillis() - startTime;
|
2014-01-03 17:08:36 +00:00
|
|
|
if (sleepTime > 0) {
|
|
|
|
try {
|
|
|
|
Thread.sleep(sleepTime);
|
|
|
|
} catch (InterruptedException e) {
|
|
|
|
// let thread exit
|
|
|
|
return;
|
|
|
|
}
|
2014-01-03 16:36:27 +00:00
|
|
|
}
|
2014-01-03 17:08:36 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
private void doOperation() {
|
2014-01-03 16:36:27 +00:00
|
|
|
for (int i = 0; i < iterationsPerThread; i++) {
|
|
|
|
Integer current = result.get();
|
|
|
|
while (! result.compareAndSet(current, current + 1)) {
|
|
|
|
current = result.get();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}).start();
|
|
|
|
}
|
|
|
|
|
|
|
|
synchronized (threadDoneCount) {
|
|
|
|
while (threadDoneCount.get() < threadCount) {
|
|
|
|
try {
|
|
|
|
threadDoneCount.wait();
|
|
|
|
} catch (InterruptedException e) {
|
|
|
|
// let thread exit
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
long expectedResult = threadCount * iterationsPerThread;
|
|
|
|
Integer resultValue = result.get();
|
|
|
|
if (resultValue != expectedResult) {
|
|
|
|
throw new IllegalStateException(resultValue + " != " + expectedResult);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public static void main(String[] args) {
|
|
|
|
runTest(10, 100);
|
|
|
|
}
|
|
|
|
}
|