Created
March 18, 2015 09:51
-
-
Save stuartrexking/d1810bfa8d88671a6c51 to your computer and use it in GitHub Desktop.
Thread Interference
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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