Skip to content

Instantly share code, notes, and snippets.

@stuartrexking
Created March 18, 2015 09:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stuartrexking/d1810bfa8d88671a6c51 to your computer and use it in GitHub Desktop.
Save stuartrexking/d1810bfa8d88671a6c51 to your computer and use it in GitHub Desktop.
Thread Interference
package com.stuartrexking.blog;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;
final class ThreadInterference {
private enum Counter {
INSTANCE;
private int count = 0;
public void increment() {
count = count + 1;
}
public void decrement() {
count = count - 1;
}
public int value() {
return count;
}
}
private enum SynchronizedCounter {
INSTANCE;
private int count = 0;
public synchronized void increment() {
count = count + 1;
}
public synchronized void decrement() {
count = count - 1;
}
public int value() {
return count;
}
}
public int withInterference() throws InterruptedException {
CountDownLatch latch = new CountDownLatch(2);
ExecutorService executorService = Executors.newFixedThreadPool(2);
executorService.execute(runnable(latch));
executorService.execute(runnable(latch));
latch.await();
return Counter.INSTANCE.value();
}
public int withoutInterference() throws InterruptedException {
CountDownLatch latch = new CountDownLatch(2);
ExecutorService executorService = Executors.newFixedThreadPool(2);
executorService.execute(synchronizedRunnable(latch));
executorService.execute(synchronizedRunnable(latch));
latch.await();
return Counter.INSTANCE.value();
}
private Runnable runnable(CountDownLatch latch) {
return () -> {
IntStream.range(0, 1000).parallel().forEach(
iteration -> {
Counter.INSTANCE.increment();
Counter.INSTANCE.decrement();
}
);
latch.countDown();
};
}
private Runnable synchronizedRunnable(CountDownLatch latch) {
return () -> {
IntStream.range(0, 1000).parallel().forEach(
iteration -> {
SynchronizedCounter.INSTANCE.increment();
SynchronizedCounter.INSTANCE.decrement();
}
);
latch.countDown();
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment