Skip to content

Instantly share code, notes, and snippets.

@northerngosling
Created May 15, 2020 14:11
Show Gist options
  • Save northerngosling/7933690ce7ccd47c297aee2b5618e34c to your computer and use it in GitHub Desktop.
Save northerngosling/7933690ce7ccd47c297aee2b5618e34c to your computer and use it in GitHub Desktop.
Class demonstrating the lack of happens-before link
package concurrency;
public class HappensBefore {
private static class Value {
private int index;
void increment() {
index++;
}
void print() {
if (index == 0)
System.out.println("got zero");
}
}
public static void main(String... args) throws InterruptedException {
for (int i = 0; i < 10_000; i++) {
Value value = new Value();
Runnable r1 = () -> value.increment();
Runnable r2 = () -> value.print();
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
t2.start();
t1.join();
t2.join();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment