3 ms·
> I thought that the problem lay in 4 where you might read a partial update of the pointer, possibly giving weird results. Is he saying that it might get assign
by EdiX 13y ago
> I thought that the problem lay in 4 where you might read a partial update of the pointer, possibly giving weird results. Is he saying that it might get assigned first and then constructed afterwards?
Yes. In some versions of java the code:
x = new X()
results in assigning to x a reference to a new uninitialized object X and then a call to the constructor.
Reference assignment in java is always atomic, it is guaranteed by the memory model.
- barrkel 13y agoNo. x = new X() should not make x assigned such that it is visible inside the constructor of X. The behaviour in the post can only been seen with concurrency. The issue here is the lack of a write barrier at the point of publishing the reference to the newly constructed object, and the lack of a read barrier at the point of reading the reference to the newly constructed object. You want to stop both writes moving forward in time (the writes in the constructor happening after the write that publishes the object) and reads moving backwards in time (the reads on the other thread reading the old values of the constructed object, rather than the initialized values - may be caused by e.g. satisfying the read from per-CPU cache). Java's volatile acts both ways; writes are write barriers and reads are read barriers.