Say I have two threads and an object. One thread assigns the object:
public void assign(MyObject o) {
myObject = o;
}
Another thread uses t
There are some confusing comments here: to clarify, your code is incorrect as it stands, assuming two different threads call assign()
and use()
.
In the absence of volatile
, or another happens-before relationship (for example, synchronization on a common lock) any write to myObject
in assign()
is not guaranteed to be seen by the thread calling use()
-- not immediately, not in a timely fashion, and indeed not ever.
Yes, volatile
is one way of correcting this (assuming this is incorrect behaviour -- there are plausible situations where you don't care about this!).
You are exactly correct that the 'use' thread can see any 'cached' value of myObject
, including the one it was assigned at construction time and any intermediate value (again in the absence of other happens-before points).