Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 4

Understanding and Using the Volatile Keyword

This lesson is built with resources from youtube.com, baeldung.com and 1 more site.

Hello! In our last lesson, we successfully implemented and tested a memory visibility bug using the JCStress framework. By observing a partially constructed object in the UnsafePublication test, you gained firsthand, practical proof of how CPU caching and instruction reordering can break concurrent code. You now have a concrete problem in your hands—code that is demonstrably incorrect.

Today, we will introduce the solution. This lesson focuses on Java's primary mechanism for enforcing visibility: the volatile keyword. Our goal is to understand precisely what guarantees volatile provides, how it works under the hood, and how to apply it to fix the very visibility problems you learned to create. By the end of this session, you'll be able to confidently use volatile to ensure that changes to shared variables are seen by other threads in a predictable manner.

The Problem Revisited: Local Caches vs. Main Memory

Let's quickly recall the root of our problem. In a multi-core system, each CPU core has its own local caches to speed up memory access. When a thread running on one core modifies a shared variable, that change might only be written to its local cache. Another thread running on a different core, with its own cache, will not see this update until it is flushed to main memory and the second thread's cache is invalidated and refreshed.

This diagram illustrates the core issue. Without `volatile` (left), threads t1 and t2 might continue to see the old value of x=10 from their local caches, even after thread t3 has updated the value to 20 in main memory. With `volatile` (right), all threads are forced to read the variable directly from main memory, ensuring they see the most recent value.

This lag between a write in one thread and its visibility in another is the essence of a visibility problem.


The volatile Solution: Ensuring Visibility

The volatile keyword is a direct instruction to the Java compiler and the JVM to handle a variable in a special way, specifically to solve this visibility problem. When a variable is declared volatile, the JVM ensures two critical things:

  1. Writes go to main memory: Any write to a volatile variable is immediately flushed from the CPU's local cache to main memory.
  2. Reads come from main memory: Any read of a volatile variable bypasses the CPU's local cache and reads the value directly from main memory.

This mechanism is often implemented using a hardware instruction known as a memory barrier (or memory fence). A memory barrier enforces an ordering constraint on memory operations, effectively telling the CPU to "commit all pending writes to main memory now" or "clear local read caches and get the latest from main memory."

This diagram shows the mechanism of `volatile`. A write by Thread 1 is immediately flushed to main memory. A memory barrier ensures this operation is not reordered and is visible. A subsequent read by Thread 2 is forced to go directly to main memory, ensuring it sees the update made by Thread 1.

To get a formal understanding of this guarantee, the following two resources provide excellent, concise explanations.

Guide to the Volatile Keyword in Java

This article from Baeldung clearly explains how volatile addresses cache coherence and reordering.

Please read section 4, volatile Memory Order. It directly describes how applying the volatile modifier solves the problems of visibility and reordering.

Java Volatile Keyword

This tutorial from Jenkov.com provides another clear perspective on the visibility guarantee.

Focus on the section titled The Java volatile Visibility Guarantee. This part explains that all writes are immediately sent to main memory and all reads come directly from main memory.


Practical Application: Fixing the UnsafePublication Test

Now, let's apply this knowledge. In the previous lesson, you created a JCStress test named UnsafePublication that produced "interesting" results (0, 1, 2, 3), proving that a consumer thread could see a partially constructed object.

The fix is remarkably simple. You only need to add the volatile keyword to the declaration of the shared object reference.

Your Task:

  1. Open your JCStress project from the previous lesson.
  2. Find your UnsafePublication test class.
  3. Modify the declaration of the MyObject o; field to be private volatile MyObject o;.
  4. Rerun the test (mvn clean verify and java -jar target/jcstress.jar).
  5. Analyze the results in results/index.html.

You will now observe that the "interesting" states (0, 1, 2, 3) have disappeared. The only outcomes should be -1 (consumer ran before publisher) and 4 (consumer saw a fully constructed object). You have successfully fixed the visibility bug.


The Happens-Before Guarantee: volatile's Superpower

You might be wondering why making the reference o volatile also fixed the visibility of the fields inside MyObject (e.g., x00, x01). This is because volatile provides a guarantee that is stronger than just visibility of the variable itself. It establishes a happens-before relationship.

The Java Memory Model specifies the volatile variable rule:

A write to a volatile field happens-before every subsequent read of that same field.

This has a powerful consequence: When thread B reads a volatile variable that was just written by thread A, thread B is guaranteed to see not only the volatile variable's new value but also all other variable changes that thread A made before it wrote to the volatile variable.

In our UnsafePublication example:

  1. The writes to the fields (x00 = 1, x01 = 1, etc.) inside the MyObject constructor happen.
  2. The write to the volatile variable o happens (o = new MyObject();).
  3. Because of the happens-before rule, all the writes from step 1 are guaranteed to be visible to any thread that subsequently reads the volatile variable o.

This effect, where the visibility guarantee of one volatile variable extends to other non-volatile variables, is sometimes called "piggybacking." It's a fundamental concept for writing correct concurrent code without having to make every single shared variable volatile.

The following resources explain this critical happens-before relationship.

Guide to the Volatile Keyword in Java

The Baeldung article explains the happens-before ordering and the concept of piggybacking.

Read the sections titled Happens-Before Ordering and Piggybacking. This will clarify how volatile synchronizes more than just its own value.

Java Volatile

Jakob Jenkov's video on volatile provides a great visual explanation of this extended visibility guarantee and the reordering problem it solves.

Watch these two segments: Visibility Guarantee: Explains how writing to a volatile variable flushes other visible variables to main memory. Instruction Reordering and Happens-Before: This core segment explains how instruction reordering can break visibility and how the volatile happens-before guarantee prevents this.


The Limits of volatile

It's crucial to understand what volatile does not do. It provides visibility and ordering, but it does not provide atomicity for compound operations.

A common mistake is to assume volatile can make an operation like count++ thread-safe. It cannot. The count++ operation is not a single, atomic step. It is three separate steps:

  1. Read the current value of count.
  2. Modify the value (increment it).
  3. Write the new value back.

If two threads execute count++ concurrently on a volatile int count, a race condition can still occur:

  • Thread A reads count (value is 5).
  • Thread B reads count (value is still 5, because Thread A hasn't written back yet).
  • Thread A increments its value to 6 and writes it back. Main memory now holds 6.
  • Thread B increments its value to 6 and writes it back. Main memory still holds 6.

The result is 6, when it should have been 7. An update was lost. volatile ensured both threads saw the initial value of 5 correctly, but it couldn't prevent them from overwriting each other's results. For compound "read-modify-write" operations, you need stronger synchronization, such as synchronized blocks or java.util.concurrent.atomic classes.

This short reading and video segment will solidify your understanding of this limitation.

Java Volatile Keyword

The Jenkov article clearly explains why volatile is not a silver bullet.

Read the section titled volatile is Not Always Enough. It describes the exact race condition scenario with a counter.

This limitation is a key diagnostic skill, and we will explore it further in a future lesson dedicated to scenarios where volatile is insufficient.


Conclusion

In this lesson, we armed ourselves with the tool to fix the visibility bugs we uncovered previously. You learned that the volatile keyword provides a powerful guarantee of visibility by ensuring that reads and writes happen directly with main memory, enforced by memory barriers.

More importantly, you now understand that volatile establishes a happens-before relationship, which not only prevents harmful instruction reordering but also extends visibility guarantees to other variables. This allowed you to fix the UnsafePublication bug with a single keyword. Finally, you learned the critical limitation of volatile: it ensures visibility, not atomicity.

Key Takeaways:

  • volatile solves visibility problems by forcing reads from and writes to main memory.
  • A write to a volatile variable happens-before any subsequent read of that same variable.
  • This happens-before guarantee makes all prior non-volatile writes from the writer thread visible to the reader thread.
  • volatile is the correct tool for ensuring visibility of simple assignments or for signaling between threads.
  • volatile is not sufficient for compound read-modify-write operations (like i++), which require atomic updates or locks.

In our next lesson, we will expand on the concept of the happens-before relationship. volatile is just one way to create this ordering guarantee. We will explore the complete set of rules in the Java Memory Model that define happens-before, giving you a comprehensive framework for analyzing the thread-safety of any concurrent code.