I've been going through Java Concurrency in Practice and trying to reproduce the examples as I go through.
I found that when trying to illustrate the no visibility problem in chapter 3 the example in the code didn't work for me so I tweaked it a little bit:
Here is the test:
Then after running it for some time:
org.junit.ComparisonFailure:
Expected :0
Actual :-1822446613
\o/
I found that when trying to illustrate the no visibility problem in chapter 3 the example in the code didn't work for me so I tweaked it a little bit:
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
import java.util.Random; | |
import java.util.concurrent.*; | |
class NoVisibility { | |
private boolean ready; | |
private int number; | |
private final ExecutorService executor; | |
private final Random random; | |
NoVisibility(ExecutorService executor, Random random) { | |
this.executor = executor; | |
this.random = random; | |
} | |
private class Reader implements Callable<Integer> { | |
@Override | |
public Integer call() throws Exception { | |
while (!ready) { | |
Thread.yield(); | |
} | |
return number; | |
} | |
} | |
int go() throws ExecutionException, InterruptedException { | |
Future<Integer> submission = executor.submit(new Reader()); | |
int randomNumber = random.nextInt(); | |
this.number = randomNumber; | |
ready = true; | |
return submission.get() - randomNumber; | |
} | |
} |
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
import org.junit.Test; | |
import java.util.Random; | |
import java.util.concurrent.ExecutionException; | |
import java.util.concurrent.ExecutorService; | |
import java.util.concurrent.Executors; | |
import static org.assertj.core.api.Assertions.assertThat; | |
public class NoVisibilityTest { | |
private ExecutorService executor = Executors.newSingleThreadExecutor(); | |
@Test | |
public void go() throws ExecutionException, InterruptedException { | |
Random random = new Random(); | |
while (true) { | |
assertThat(new NoVisibility(executor, random).go()) | |
.isEqualTo(0); | |
} | |
} | |
} |
Then after running it for some time:
org.junit.ComparisonFailure:
Expected :0
Actual :-1822446613
\o/