Reputation: 599
Effective Java - Item 66 (2nd Edition) states
In fact, synchronization has no effect unless both read and write operations are synchronized.
Suppose I have an object which is being updated by one thread and read by another thread. Synchronization on the read thread is needed for communication purpose, because as stated
In other words, the synchronization on these methods is used solely for its communication effects, not for mutual exclusion.
But if the write is performed by a single thread, why can't we get away without using synchronised during write?
Upvotes: 0
Views: 580
Reputation: 8758
Because of how happens-before works in Java Memory Model. To allow thread2 to see a new value of variable written by thread1 you need to establish happens-before relationship between this write and read (https://www.logicbig.com/tutorials/core-java-tutorial/java-multi-threading/happens-before.html). One of the ways to do it is to use synchronization (synchronized
blocks/methods, volatile
, AtomicXXX
) because releasing a lock always happens before acquiring of the same lock, write to volatile
variable happens before subsequent read of the same volatile
variable. And AtomicXXX.set()
happens before AtomicXXX.get()
for the same variable.
Upvotes: 1