Possible Duplicate:
How to simulate constructor race conditions?
How to demonstrate race conditions around values that aren't published properly?
I got the following code from 《java concurrency in practice》:
public class Holder{
private int n;
public Holder(int n){this.n = n;}
public void assertSanity(){
if(n != n) throw new AssertionError("This statement is false.");
}
}
I am just wondering the condition n != n, is this could be true under a certain circumstance?
My guess is that you are asking something similar to these questions:
I’m guessing the book is talking about the possibility of sharing a reference to an object before it is completely constructed, an act referred to is improper publishing.
Suppose that
n != nis broken down into the following steps:Then it follows that it is not hard to imagine a case in which the value of
nis changed between the first two steps. Now I know what you are thinking, “butnis never changed”. Actually, it is, because two threads could share access to an instance ofHolderbefore the constructor for that instance has completely run.