javavolatilenon-volatile

Java : Volatile variable access


I am a little confuse about how volatile variable effectively accesses from "main" memory. How's it different from a variable (non-volatile) that has a local copy ? What's the typical workflow whenever multiple threads accesses a non-volatile vs a volatile variable ? I mean how do they work behind the scene ?


Solution

  • Let's say you have a variable that can be accessed by multiple threads.

    Thread 1 looks at the variable. Because looking at shared memory is more expensive than thread-local memory, it makes a copy of the variable. (Note that an object won't be copied, just its reference.)

    Thread 2 looks at the same variable. It decides to change the variable. But Thread 1 doesn't know it! Thread 1 is still using stale data. This is a Very Bad Thing. By making it volatile, each thread must look at the original variable when accessing it. They aren't permitted to make local copies, so it won't get stale.