Volatile to many that code in Java is a mystery keyword. Most keywords are really simple to understand, but volatile to many is defined by a lot of mathematical mumbo-jumbo. Volatile is a very very simple structure, if explained right:
Writes happen-before reads.
Still a little confused? There are three basic problems in the Java (or any other) multi-threaded environment:
- Each CPU (real or virtual) may have it’s own small cache of memory data
- Any compiler along the way (including Javac, or one of the Hotspot compilers) may change the order of instructions to improve performance
- You have no real idea of which instructions in another thread will run before or after those in any other thread
As a result of these problems your update to a field may not be seen by another thread for some arbitrary amount of time, in fact it may exit before seeing your changes. Enter the volatile modifier. It’s job is to guarantee “happens-before” behavior. This means three things:
- Write operations are executed before read operations.
- Compilers are not allowed to re-order accesses to the field.
- Caches must be flushed before reading the field
The combination of these guarantees means essentially that a “read” of the field will always give the “latest” state of the field. When a new value is written, any subsequent reads (including those scheduled to “happen at the same time”) will see the new value.
October 27, 2008 at 10:23 am
[...] final keyword can serve as a hint to the Hotspot compiler at runtime. In some ways the opposite to volatile. There is another, much more important reason to declare fields, variables and parameters (almost [...]