Threadsafe Variable Access in Java
Categories: Java
Some links to information about thread-safety in Java…
This tutorial provides an excellent overview:
This article presents a lot more detail on the behaviour of the volatile
keyword, how it can be safely used - and when not:
Note that the “pattern 2” example works because (since Java 1.5) a write to a volatile variable ensures that all previous writes made by the same thread to any variable are also made visible to other threads. A write to a volatile variable is a “memory barrier” that effectively flushes cached data to memory and notifies all other CPU caches that those locations have been updated.
This article does not mention the Atomic*
types from the Java standard library, which provide some limited forms of atomic read/upate/write on a single variable - ie fit somewhere between synchronized and volatile. These are discussed in the official java tutorial referenced above.
Some other references:
-
Linux Kernel: Memory Barriers - information on exactly what a “memory barrier” is, for various CPU architectures.