EDIT: Important update thanks to @irreputable.
Unless the object has escaped during construction (see below), the assignment mMyInt=1
happens 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 as double
and long
are NOT atomic).
So, in that case the possible value is either 1 or 2.
Object can escape during construction in this kind of situation:
class Escape {
Integer mmyInt = 1;
Escape(){
new Thread(){
public void run(){
System.out.println(Escape.this.mmyInt);
}
}.start();
}
}
Although in practice it probably rarely happens, in the above case, the new thread can observe an not fully constructed Escape
object and thus in theory get an mmyInt
value of null
(AFAIK you still won't get some random memory location).
What if it it is a HashMap
object? The instance variable mMyMap
has original value. Then, the first
thread calls "mMyMap = new HashMap();"
The second thread calls "return
mMyMap;" Can the second thread get
null, or can it only get original or
new HashMap object?
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 observe null
.
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 of map
. Meanwhile thread2 comes and observe an partially constructed object.
class Clever {
Map map;
Map getMap(){
if(map==null){
map = deriveMap(); }
return map;
}
}
JDK has a similar construct in the String
class (not exact quote):
class String {
int hashCode = 0;
public int hashCode(){
if(hashCode==0){
hashCode = deriveHashCode();
}
return hashCode;
}
}
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 them volatile
will make their assignment atomic.