I'm reading "Java Concurrency in Practice" and trying to write a piece of code that will show that the class presented as an example in chapter 3.5.1 can indeed introduce problems.
public class Holder {
public int n;
public Holder(int n) {
this.n = n;
}
public void assertSanity() {
if (n != n) {
throw new AssertionError("sanity check failed!!");
}
}
}
It's said there that if used in the following way(I believe it's about the fact that the field is public, a concurrency problem may happen.
public Holder holder;
public void initialize() {
holder = new Holder(42);
}
So I've come up with this code to see if anything bad happens.
public class SanityCheck {
public Holder holder;
public static void main(String[] args) {
SanityCheck sanityCheck = new SanityCheck();
sanityCheck.runTest();
}
public void runTest() {
for (int i = 0; i < 100; i++) {
new Thread() {
@Override
public void run() {
while (true) {
if (holder != null) {
holder.assertSanity();
}
try {
Thread.sleep(1);
} catch (InterruptedException e) {
}
}
}
}.start();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
initialize();
}
public void initialize() {
holder = new Holder(42);
}
}
But nothing bad happens, no AssertionError has been thrown.
Could you please help me figure out why this code doesn't brake anything?
Thank you in advance for your time.