Created
November 18, 2017 11:56
-
-
Save polyglotpiglet/48879eba4c09397a9991ade85f4a0d4c to your computer and use it in GitHub Desktop.
NoVisibility thread example
This file contains hidden or 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; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment