Fundamentals 4 min read

Understanding the volatile Keyword and Memory Visibility in Java

The article explains how the volatile keyword ensures prompt visibility of variables across threads, illustrates its effect with a concurrent increment example, highlights that visibility does not guarantee atomicity, and introduces CAS as a solution for correct concurrent updates.

Selected Java Interview Questions
Selected Java Interview Questions
Selected Java Interview Questions
Understanding the volatile Keyword and Memory Visibility in Java

The volatile keyword ensures that the variable it decorates is promptly visible in main memory, causing updates to be immediately propagated to each thread’s local cache.

Consider two threads, A and B, both incrementing the same int counter.

Initially each thread reads the current value of count from the CPU’s cache into its own local memory.

If volatile is not used, thread A may finish first, write count = 1 back to main memory, while thread B still holds the old value 0 in its local cache; after B adds 1 it also writes 1 , so the final result remains 1 instead of the expected 2 .

When volatile is applied, after thread A updates count to 1 and flushes it to main memory, thread B is forced to read the latest value from main memory, so it increments from 1 to 2 .

Summary: Adding volatile forces every thread to read the value from main memory; without it, threads read from their own local caches.

Note: Memory visibility alone does not guarantee atomicity. Even with volatile , if both threads read the same value simultaneously and increment it, the final result may still be incorrect.

Only when the two threads execute sequentially (e.g., with a noticeable time gap) does volatile appear to work, because the operations are not truly concurrent.

To achieve correct concurrent increments, the CAS (Compare‑And‑Set) technique can be used: read the current value, compare it with the expected old value, and update only if they match, thereby avoiding the race condition described above.

The above is the author’s personal understanding and should be taken as reference only.

JavaconcurrencyCASvolatilememory visibility
Selected Java Interview Questions
Written by

Selected Java Interview Questions

A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.