Beginner Topic 15 of 51 Concurrency & Parallelism
Volatile and Visibility
Ensuring one thread's writes are seen by others.
How it works
Visibility concerns when a write by one thread becomes observable by others. Without synchronization, a thread may keep values in registers or caches, and compilers may reorder operations, so another thread might never see an update. In Java, volatile guarantees visibility and ordering of accesses to a variable, establishing happens-before edges, but not atomicity of compound operations. In C and C++, volatile prevents certain compiler optimizations for hardware access but does not provide thread synchronization; atomics do.
Where it is used
Stop flags for threads, publishing configuration, double-checked locking in Java and status variables read by many threads use volatile or atomics for visibility.
Common pitfall
Using volatile for counters, as in count++, is not thread-safe because read-modify-write is not atomic. C and C++ volatile is not a substitute for atomics, a common misconception. Visibility bugs depend on JIT, hardware and timing and may appear only in production. Use proper synchronization, atomics or locks, and understand the language memory model.
Where it fits in the course
Volatile and Visibility is topic 15 of 51 in Concurrency & Parallelism, rated Beginner. It follows Memory Barriers. The next topic is Starvation and Livelock.
Practice and explore
- Open the interactive lesson, with a mini quiz.
- Take the Concurrency & Parallelism quiz.
How to study this topic
- Read the explanation above and restate the definition in your own words.
- Open the interactive lesson and answer its mini quiz.
- Read the common pitfall, then write a short example that avoids it.
- Check your understanding in the Concurrency & Parallelism quiz, and revisit the topic if you miss a question.
Frequently asked questions
What is Volatile and Visibility?
Where do people use Volatile and Visibility?
What is the most common mistake with Volatile and Visibility?
What should I learn before this topic?
How can I practice it?
Is Volatile and Visibility hard to learn?
How long does it take to learn Volatile and Visibility?
Which topics are related to Volatile and Visibility?
What should I study after Volatile and Visibility?
Related topics
- Memory Barriers (Concurrency & Parallelism)
- Starvation and Livelock (Concurrency & Parallelism)
- Compare-and-Swap (Concurrency & Parallelism)
- Priority Inversion (Concurrency & Parallelism)