Suppose I have a instance variable that has original value:
Integer mMyInt = 1;
There are two threads.
The first changes mMyInt by calling:
void setInt() {
mMyInt = 2;
}
The second thread gets mMyInt by calling:
Integer getInt() {
return mMyInt;
}
Both threads don’t use synchronization.
My questions is, what is the possible value the the second thread can get from getInt()? Can it be only 1 or 2? Can it get null?
Thanks
EDIT: Important update thanks to @irreputable.
Unless the object has escaped during construction (see below), the assignment
mMyInt=1happens before any access to the getter/setter. Also in java, object assignment is atomic (there is 0 chance that you observe some invalid address assigned. Be careful because 64bit primitive assignments, such asdoubleandlongare NOT atomic).So, in that case the possible value is either 1 or 2.
Object can escape during construction in this kind of situation:
Although in practice it probably rarely happens, in the above case, the new thread can observe an not fully constructed
Escapeobject and thus in theory get anmmyIntvalue ofnull(AFAIK you still won’t get some random memory location).When “Object reference assignment is atomic”, it means that you will NOT observe an intermediate assignment. It’s either the value before, or the value after. So if the only assignment that is happening is
map = someNonNullMap();after the construction has completed (and the field was assigned a non null value during the construction) and the object has not escaped during the construction, you can’t observenull.Update:
I consulted a concurrency expert, and according to him, the Java Memory Model allows compilers to reorder assignment and object construction (while in practice I imagine that would be highly unlikely).
So for example in the below case, thread1 can allocate some heap, assign some value to
map, the continue construction ofmap. Meanwhile thread2 comes and observe an partially constructed object.JDK has a similar construct in the
Stringclass (not exact quote):This DOES work because the non-volatile cache is primitive and not an object, according to the same concurrency experts.
These problems can be avoided by introducing an happens before relationship. In the cases above, one could do this by declaring the members
volatile. Also for 64bit primitive, declaring themvolatilewill make their assignment atomic.