Skip to main content

Welcome to a Grasp lesson

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

Lesson 6

Limitations of `volatile` for Thread Safety

This lesson is built with resources from youtube.com, pvs-studio.com and 1 more site.

Hello! In our last lesson, we established a formal framework for reasoning about memory visibility using the happens-before relationship. You saw how volatile creates a happens-before edge, guaranteeing that writes to a variable are visible to subsequent reads of that same variable. This is a powerful guarantee for visibility and ordering.

Today, we'll explore a critical limitation of this guarantee. Visibility alone is not always enough to ensure thread safety. This lesson focuses on diagnosing common scenarios where volatile is insufficient because it does not provide atomicity. Understanding this distinction is a crucial step toward writing truly robust concurrent code.

Let's begin with a high-level comparison of the tools at our disposal.

This chart provides a quick overview of the guarantees offered by Java's `volatile`, `synchronized`, and `Atomic` classes. Notice the key difference: `volatile` guarantees visibility, but not atomicity, which is the central theme of today's lesson.

The Gap Between Visibility and Atomicity

In concurrent programming, an operation is atomic if it appears to the rest of the system to occur instantaneously and indivisibly. It either completes entirely or not at all, and no other thread can observe it in a halfway state. While volatile ensures that a thread will always see the most recent value written by another thread (visibility), it does nothing to prevent multiple threads from interfering with each other during operations that are not inherently atomic.

The most classic example of this is the increment operation, counter++. While it looks like a single action in your code, it is, in fact, a compound operation consisting of three distinct steps:

  1. Read: Get the current value of counter.
  2. Modify: Add one to the value in a temporary location (like a CPU register).
  3. Write: Store the new value back into counter.

The problem is that another thread can perform its own operations between these steps, leading to a "lost update." Let's see this in action.

Java's Atomic and volatile, under the hood on x86 - Marc's Blog

Marc Brooker, an engineer at AWS, wrote this excellent blog post demonstrating why volatile is not atomic.

Start by reading the introduction, which clearly states the problem: an increment is three operations. Then, review the experiment where he runs a simple multi-threaded counter. Pay close attention to the results for the plain int, the volatile int, and the AtomicInteger. Note how volatile fails to produce the correct result and is also significantly slower under contention.

The experiment in the article confirms our theory: even with volatile, the final count is incorrect. This is because volatile doesn't stop two threads from reading the same value before either has a chance to write its updated value back.

The following short video provides a clear, step-by-step visualization of this "lost update" race condition.

Using volatile vs AtomicInteger in Java concurrency

This clip from Defog Tech animates the interleaving of the read-modify-write sequence between two threads.

Watch the section from the beginning of the core explanation. The narrator walks through exactly how two threads, both trying to increment a value, can end up with the same final result, effectively losing one of the increments.


Why volatile is Not Atomic: A Look Under the Hood

To truly understand why volatile provides visibility but not atomicity, it's helpful to look at what the JVM and CPU are doing. This ties directly into the low-level system design concepts you're interested in.

As you know from our previous lessons, volatile works by instructing the compiler and CPU to use memory barriers. A volatile write ensures that its value is flushed to main memory. A volatile read ensures it reads from main memory. However, this barrier doesn't "lock" the variable during a read-modify-write sequence.

In contrast, classes like AtomicInteger use special hardware instructions that are atomic. The most common is Compare-And-Swap (CAS).

Let's return to Marc Brooker's article, as he provides a fantastic breakdown of the generated assembly code for both approaches.

Java's Atomic and volatile, under the hood on x86 - Marc's Blog

This section dives into the machine instructions generated by the JIT compiler.

Read the section that begins with the assembly for the volatile version. Notice it's a simple sequence of mov (load), inc (increment), and mov (store), followed by a lock addl which acts as a memory barrier. Then, examine the AtomicInteger assembly. The key instruction is lock cmpxchg (compare-and-exchange), which is the hardware's atomic guarantee. The article explains how this instruction and the surrounding retry loop work to ensure atomicity.

The difference is stark:

  • volatile: read -> modify -> write -> memory_barrier. The sequence itself is not protected. Another thread can jump in between the read and the write.
  • AtomicInteger (using CAS): loop { read -> calculate_new -> atomic_compare_and_write(if_value_is_still_the_same) }. The critical compare_and_write step is an indivisible hardware operation. If the value has changed since the read, the write fails, and the loop retries. This ensures no updates are lost.

Diagnosing Scenarios: Patterns of Failure

Now that you understand the "why," let's focus on diagnosing the "where." Non-atomic operations on volatile variables often fall into recognizable patterns.

Pattern 1: Check-Then-Act

This is a broader pattern where a thread reads a variable to make a decision, and then acts on that decision. If another thread can change the variable between the "check" and the "act," a race condition occurs.

volatile int itemsInCart = 0;

// Called by multiple threads
public void addItem() {
    if (itemsInCart < 10) { // Check
        // some delay can happen here
        itemsInCart++;      // Act
    }
}

If itemsInCart is 9, two threads can both execute the if check and find it to be true. Both will then proceed to increment the counter, and the final value could become 11, violating the business rule.

The next video illustrates this exact problem with a similar counter example.

Java Volatile

Jakob Jenkov demonstrates the check-then-act failure pattern.

Watch the segment from "not always enough". He explains how two threads can simultaneously pass a check (count is not equal to 10) and then both perform an increment, leading to an incorrect state. This shows that the entire if-then-increment block must be atomic, which volatile does not provide.

Pattern 2: Real-World Code Smells

These issues aren't just academic. They appear in real production code. Static analysis tools are often used to find such potential bugs. The following article analyzes several examples found in the popular database tool DBeaver.

Volatile, DCL, and synchronization pitfalls in Java

This PVS-Studio blog post first recaps the counter++ problem and then dives into real-world code snippets where volatile is used non-atomically.

First, read the section "Race" for another clear demonstration of the increment problem. Then, focus on the "Case study" section. Analyze the three code fragments from DBeaver. For each one (runningOperations, drawCount, initializedCount), consider why the analyzer flags the non-atomic increment/decrement and what the potential, even if unlikely, risk is.

As the article points out, sometimes the context (e.g., code only being called from a single UI thread) makes the race condition unlikely, but the code is still fragile and technically incorrect. A change in how that code is used in the future could easily introduce a bug.

Pattern 3: The Double-Checked Locking (DCL) Idiom

A famous and more complex example is the Double-Checked Locking pattern, used for lazy initialization of singleton objects.

// Pre-Java 5: BROKEN
public class MySingleton {
    private static Helper helper = null;
    public static Helper getHelper() {
        if (helper == null) {
            synchronized(MySingleton.class) {
                if (helper == null) {
                    helper = new Helper();
                }
            }
        }
        return helper;
    }
}

Prior to Java 5, this code was broken. A thread could see a non-null reference to helper before its constructor had finished running, leading to access to a partially initialized object. This was due to instruction reordering.

The fix in Java 5+ was to declare the field volatile:
private static volatile Helper helper = null;

In this specific pattern, volatile is sufficient. The happens-before guarantee of the volatile write to helper ensures that all writes inside the Helper constructor are visible before any thread sees the non-null reference to helper. This is a case of using volatile for its visibility and ordering guarantees, not for atomicity on the variable itself. However, it's a common source of confusion and demonstrates a scenario where a deep understanding of the memory model is essential.

Volatile, DCL, and synchronization pitfalls in Java

The same PVS-Studio article provides a great analysis of DCL.

Read the section on DCL. It explains why the pattern was broken and how volatile fixed it by enforcing the happens-before principle. Also, read the next section, "Or is it, though?!", which makes the important practical point that DCL may be an unnecessary micro-optimization in modern JVMs where synchronized performance has improved significantly.


Conclusion

In this lesson, we dissected the critical difference between visibility and atomicity. You've seen that while volatile is an essential tool for ensuring changes to a variable are seen by other threads, it offers no protection against race conditions in compound operations.

Key Takeaways:

  • volatile guarantees visibility, not atomicity. It ensures that reads and writes go to main memory, but it does not make a sequence of operations (like read-modify-write) indivisible.
  • Compound operations are the danger zone. Any operation that involves more than a single read or a single write is non-atomic and a potential source of race conditions. Common examples include i++ and check-then-act logic.
  • The root cause is thread interleaving. Race conditions occur because the scheduler can pause one thread in the middle of a compound operation and let another thread run, leading to lost updates or inconsistent state.
  • Diagnosis requires pattern recognition. Look for read-modify-write sequences (++, --, +=) and check-then-act blocks (if (check) { act }) on shared volatile variables.
  • Solutions require true atomicity. To fix these issues, you must use a mechanism that guarantees atomicity, such as a synchronized block or methods from the java.util.concurrent.atomic package like AtomicInteger.

We've established that synchronized is one of the primary solutions for atomicity. In our next lesson, we will begin our deep dive into advanced locking by comparing the built-in synchronized keyword with the more powerful and flexible ReentrantLock class, exploring features that give you finer control over concurrent access.