Skip to main content

Welcome to a Grasp lesson

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

Lesson 2

Understanding Visibility Challenges in Concurrent Programming

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

In our previous lesson, we explored how instruction reordering by compilers and CPUs can break the intuitive, sequential logic of your code, leading to surprising outcomes in a multithreaded context. Today, we'll investigate the other major culprit behind concurrency bugs: memory visibility. We will see how the physical architecture of modern computers, specifically CPU caches, can prevent one thread from seeing changes made by another, even when no reordering occurs.

Your goal for this lesson is to learn how to identify these visibility issues in concurrent code. Understanding this problem is a prerequisite for writing correct, high-performance concurrent applications, as it reveals why direct, unsynchronized access to shared data is fraught with danger.

The Source of the Problem: The Memory Hierarchy

To understand visibility, we first need to appreciate why it's a problem in the first place. Modern CPUs are incredibly fast, but main memory (RAM) is comparatively slow. To bridge this speed gap, CPUs use multiple levels of smaller, much faster memory areas called caches.

This block diagram shows the typical memory hierarchy. The CPU has its own ultra-fast registers and one or more levels of cache (L1, L2). These are much faster to access than the main system RAM. Data is moved between RAM and these caches for faster processing.

When a CPU core needs to read or write data, it interacts with its local cache. This is a crucial performance optimization. But what happens when multiple threads are running on different cores, each with its own private cache?

The following video from Jakob Jenkov explains how the conceptual Java Memory Model, with its thread stacks and heap, is mapped onto this physical hardware.

The Java Memory Model - The Basics

This video, "The Java Memory Model - The Basics", provides a great visual mapping from Java's abstract model to physical hardware.

Please watch the segment from hardware architecture. Focus on how the heap and thread stacks, which reside in main memory (RAM), are accessed by CPUs through their local caches and registers.

The key takeaway is that each CPU core works with its own copy of data stored in its local cache. This simple fact is the root cause of visibility problems.


The Visibility Problem

A visibility problem occurs when a change made to a shared variable by one thread is not visible to another thread. Because threads can run on different CPU cores, each with its own cache, this happens frequently.

  1. Thread A runs on Core 1. It reads a shared variable x from main memory into its local cache and then modifies it. The updated value of x now lives in Core 1's cache.
  2. Thread B runs on Core 2. It needs to read the variable x. It might read the original, stale value from main memory, because the updated value from Core 1's cache has not yet been written back to main memory.

This scenario is depicted perfectly in the diagram below. Different threads, represented by the colored figures, have their own CPU caches. Some threads end up working with "stale data" because their caches are not synchronized with the main memory that other threads have updated.

This diagram shows multiple threads interacting with main memory. Each has its own CPU cache. Updates from one thread might not be immediately visible to others, leading to some threads operating on stale data. The diagram also correctly notes that compiler reordering contributes to this class of problems.

Let's ground this with a more formal explanation.

Java Memory Model | Concurrency Interview

This article from AlgoMaster.io gives a concise overview of the technical reasons for visibility problems.

Please read the introductory section and the section titled "Why the JMM Exists". Pay attention to the four main reasons listed: CPU Caches, Store Buffers, Compiler Reordering, and CPU Instruction Reordering. This reinforces that caching and reordering are intertwined causes.

As the article states, without the JMM's rules, your Java program's behavior would be unpredictable across different hardware.


Identifying Visibility Bugs in Practice

Now that you understand the theory, let's look at how to spot these issues in real code. Visibility bugs often manifest in subtle ways that are hard to debug because they might only appear under specific hardware conditions or heavy load.

Case Study 1: The Infinite Loop

A very common pattern is using a simple boolean flag to signal a worker thread to stop. Consider this code:

public class Worker implements Runnable {
    private boolean running = true;

    public void stop() {
        running = false;
    }

    @Override
    public void run() {
        while (running) {
            // ... do some work
        }
        System.out.println("Worker thread has stopped.");
    }
}

// In another thread (e.g., the main thread)
Worker worker = new Worker();
new Thread(worker).start();
Thread.sleep(1000);
worker.stop(); // Tell the worker to stop

You would expect the worker thread to stop shortly after stop() is called. However, this program might never terminate. Here's why:

  1. The worker thread starts and reads running = true into its core's cache.
  2. The JIT compiler might perform an optimization. Since the loop itself never changes running, the compiler might transform while(running) into if(running) { while(true) { ... } }. The check is effectively hoisted out of the loop.
  3. When the main thread calls stop(), it updates running = false. This write might only go to the main thread's core cache.
  4. The worker thread, spinning in its optimized infinite loop, never re-checks the value of running from main memory and thus never sees the update. It loops forever.

This is a classic visibility bug. The AlgoMaster article you just looked at discusses this very problem.

Case Study 2: Stale Data Reads

In the last lesson, we saw how reordering a = 1; and flg = true; could cause another thread to see flg as true but read an old value for a. Caching creates a similar, and often indistinguishable, problem.

Even if the instructions are not reordered:

  1. Thread 1 (Producer) executes a = 1; followed by flg = true;. Both writes go to its local cache.
  2. The cache is flushed to main memory. It's possible for the change to flg to become visible in main memory before the change to a.
  3. Thread 2 (Consumer) reads flg and sees true. It proceeds to read a.
  4. Because the update to a is not yet visible in main memory, Thread 2 reads the old, stale value of a.

From the outside, the symptom is identical to instruction reordering. The following explanation from a Stack Overflow discussion captures this perfectly.

multithreading - How to demonstrate Java instruction reordering problems? - Stack Overflow

This answer on Stack Overflow explains how caching and reordering produce similar observable effects.

Read the short paragraph under the "Explanation" heading that begins with this sentence. It elegantly states that even if instructions execute in order, cache flush timing can make it appear as if they were reordered.

Case Study 3: The Broken Counter

Let's look at a piece of code you can run yourself that demonstrates these effects. Here, two threads share a single Runnable object and increment a counter.

The Java Memory Model - The Basics

Let's return to Jakob Jenkov's video. He demonstrates a simple counter that produces incorrect results due to a lack of synchronization.

Watch the final segment of the video, where he shows what happens when two threads share the runnable. The expected final count is 2,000,000, but the actual result is consistently lower.

This bug is a combination of two issues:

  1. Atomicity: The operation count++ is not a single instruction. It's a read-modify-write sequence (read count, add 1, write count). A thread can be preempted in the middle of this sequence, causing updates to be lost.
  2. Visibility: When Thread A increments the count, the new value is in its local cache. When Thread B performs its increment, it might read the stale value of count from main memory, effectively overwriting Thread A's work.

Both problems stem from unsynchronized access to shared mutable state. The key takeaway is that when you see shared variables being read and written by multiple threads without any synchronization mechanism (like volatile or synchronized, which we'll cover soon), you should immediately suspect potential visibility and atomicity bugs.


Key Takeaways

  • The performance gap between CPUs and RAM necessitates CPU caches, which are small, fast, per-core memory stores.
  • Visibility Problem: When one thread updates a shared variable, the change is written to its local cache. Other threads running on different cores may not see this update immediately, and instead read a stale value from main memory or their own caches.
  • Symptoms of Visibility Bugs: Common patterns include infinite loops when using a flag for termination, reading inconsistent or stale object state, and incorrect results in calculations like the shared counter.
  • Interplay with Reordering: The effects of caching can make it appear as though instructions were reordered, even if they weren't. From a practical standpoint, both issues require the same solutions.

What's Next

You can now recognize the fundamental dangers of unsynchronized memory access: instruction reordering and memory visibility. You know why these problems exist and what they look like in code.

In our next lesson, we will begin exploring the solution. We'll introduce the volatile keyword, a special tool in Java that provides memory visibility guarantees, and see how it can be used to fix the very bugs we've identified today.