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.

The lesson behind it →
More on Memory model