Skip to content

Instantly share code, notes, and snippets.

@polyglotpiglet
Created November 18, 2017 11:56
Show Gist options
  • Select an option

  • Save polyglotpiglet/48879eba4c09397a9991ade85f4a0d4c to your computer and use it in GitHub Desktop.

Select an option

Save polyglotpiglet/48879eba4c09397a9991ade85f4a0d4c to your computer and use it in GitHub Desktop.
NoVisibility thread example
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