volatile and Long/Double Variables: Atomicity Guarantee
What you'll learn: How volatile prevents word tearing when reading and writing 64-bit long and double values in multi-threaded environments.
The 64-Bit Atomicity Problem
On 32-bit systems, reading or writing a 64-bit value (long or double) can be split into two separate 32-bit operations. Without synchronization, one thread might see a bizarre hybrid value—half from one write, half from another. This problem is called word tearing.
Imagine a long variable being updated from 0x0000000000000000 to 0xFFFFFFFFFFFFFFFF. A concurrent reader on a 32-bit system might see 0x00000000FFFFFFFF or 0xFFFFFFFF00000000—values that never actually existed!
How volatile Fixes This
When you declare a long or double as volatile, the Java Memory Model guarantees atomic reads and writes—even on 32-bit architectures. The entire 64-bit value is read or written as a single, indivisible operation.
volatile long sharedCounter; // Atomic reads/writes guaranteed
volatile double sharedResult; // Atomic reads/writes guaranteed
Without volatile, the JVM specification permits non-atomic access to long and double (though many modern 64-bit JVMs do it atomically anyway—but don't rely on that!).
What volatile Does NOT Do
Remember: volatile only guarantees atomic reads and writes of individual values. It does not make compound operations like sharedCounter++ atomic. For that, you still need synchronized or atomic classes.
When This Matters
This guarantee is most critical when:
- Running on 32-bit JVMs or embedded systems
- Sharing
longordoublevariables between threads - You need visibility and atomicity for single read/write operations
Key Takeaway: Declaring long or double variables as volatile guarantees atomic 64-bit reads and writes, preventing word tearing on 32-bit systems while also ensuring visibility across threads.