Memory modelmedium0-2 years
When would you use synchronized, and when volatile?
synchronized gives mutual exclusion plus visibility: use it for read-modify-write and for invariants across several fields. volatile gives visibility only: use it for a flag another thread polls, or a reference to an immutable snapshot that one thread replaces. Never volatile for a counter.
PreviousWhat is the Java Memory Model, and what does happens-before guarantee?Next Why would you choose ReentrantLock over synchronized?