Core Java

False Sharing and Cache Lines: One Padded Field, a Measurable Slowdown

Imagine two threads that never touch each other’s data. No locks, no shared variables, no contention in the code. Yet the program runs several times slower than it should. This is false sharing, and it is one of the few performance bugs that you cannot see by reading the source.

What a Cache Line Really Is

First, a quick reminder of how a CPU reads memory. It does not fetch single bytes. Instead, it moves memory in fixed blocks called cache lines, which are commonly 64 bytes on mainstream x86 and many Arm server chips. Every core keeps its own copy of the lines it uses.

Because several cores may hold the same line, the hardware needs a rule to keep them consistent. Modern CPUs use a coherence protocol, usually a variant of MESI. In short, a core must own a line exclusively before it can write to it. When another core wants to write to that same line, the line has to travel across.

How False Sharing Happens

Now consider two long fields declared next to each other in one object. Together they take 16 bytes, so the JVM will very likely place them inside a single 64-byte line. Thread A increments the first field, while thread B increments the second.

Logically, these writes are independent. Physically, however, both threads need exclusive ownership of the same line. As a result, the line bounces between the two cores on nearly every write. Each bounce costs far more than the increment itself. That ping-pong is false sharing: the data is not shared, but the cache line is.

Why Java Developers Meet It Often

Java hides object layout from you, so adjacent fields are easy to create by accident. Typical hot spots include per-thread counters in an array, statistics objects with several volatile fields, and ring buffer cursors. Even the JDK has to defend against it, which is why JEP 142 introduced the @Contended annotation for its own internal classes.

What the Measurements Show

Let’s look at real numbers rather than theory. The first source is the Arm Learning Path on detecting false sharing in Java. In it, two threads update separate volatile long fields one billion times in total, first adjacent and then padded.

Five measured runs per mode from the Arm Learning Path (worker-phase seconds, sorted, lower is better). Values rounded to two decimals. Results are specific to that processor, JVM and test setup.

The gap is large and, importantly, consistent. The median drops from 15.5 seconds to 2.9 seconds, which is roughly 5.4 times faster. Moreover, the padded runs vary by only about 0.04 seconds, whereas the baseline runs spread across almost three seconds. False sharing hurts speed, and it also makes timing unpredictable.

A second, independent project tells the same story. The false-sharing-demo repository reports both a plain timing and a JMH throughput result.

JMH throughput from the m0wfo/false-sharing-demo README, in millions of operations per second (higher is better). Hardware was a 2.3 GHz Core i7 according to the project; treat the figures as one author’s run.
SourceUnpaddedPaddedGain
Arm Learning Path, median of 5 runs15.5 s2.9 sabout 5.4x
m0wfo demo, 1 billion updates53.7 s7.0 sabout 7.7x
m0wfo demo, JMH throughput148.5 M ops/s728.6 M ops/sabout 4.9x

The Price of Padding

Padding is not free. In the Arm example, @Contended grew each object from 32 bytes to 288 bytes, because the JVM reserves 128 bytes of padding on each side of a contended field by default. For a handful of hot counters that is nothing. For millions of small objects, however, it would bloat the heap and add garbage collection work.

Furthermore, padding is not a guaranteed win. One mailing-list post on Mechanical Sympathy reported a JMH test on memory-mapped writes where the padded version measured slower than the unpadded one. In other words, always measure on your own hardware before and after.

TechniqueHow it worksTrade-off
@ContendedJVM adds padding around marked fieldsNeeds -XX:-RestrictContended outside the JDK; large objects
Manual spacingUse every 16th slot of a long arrayWorks on any JVM; wastes memory by design
LongAdderSplits one counter into padded cellsBest for counters; reads are not a single atomic snapshot

Try It Yourself

You do not need JMH or special flags to see the effect. The program below uses a plain AtomicLongArray. Slots 0 and 1 sit about 8 bytes apart, so they almost always share a line. Slots 0 and 16 sit 128 bytes apart, so they never do. It runs on JDK 11 or newer with the single-file launcher.

cat > FalseSharingDemo.java <<'EOF'
import java.util.concurrent.atomic.AtomicLongArray;

public class FalseSharingDemo {
    private static final long ITERATIONS = 50_000_000L;

    static long run(int slotA, int slotB)
            throws InterruptedException {
        AtomicLongArray c = new AtomicLongArray(32);
        Thread a = new Thread(() -> work(c, slotA));
        Thread b = new Thread(() -> work(c, slotB));
        long start = System.nanoTime();
        a.start();
        b.start();
        a.join();
        b.join();
        return (System.nanoTime() - start) / 1_000_000;
    }

    static void work(AtomicLongArray c, int slot) {
        for (long i = 0; i < ITERATIONS; i++) {
            c.set(slot, c.get(slot) + 1);
        }
    }

    public static void main(String[] args)
            throws InterruptedException {
        System.out.println("CPUs: "
            + Runtime.getRuntime().availableProcessors());
        run(0, 1);
        run(0, 16);
        System.out.println("Adjacent: " + run(0, 1) + " ms");
        System.out.println("Padded:   " + run(0, 16) + " ms");
    }
}
EOF
java FalseSharingDemo.java

Please note one requirement: the machine needs at least two CPU cores. I compiled and ran this exact program on JDK 21 in a single-core sandbox, and it works there. As expected, both timings came out almost identical (829 ms against 851 ms), because two threads on one core cannot fight over a line. On a multicore machine you should see the adjacent case run clearly slower, although the exact ratio depends on your CPU.

Checklist: is it false sharing?

  • Several threads write to different fields of one object or neighbouring array slots.
  • Adding threads makes throughput flat or worse, even without locks.
  • A profiler shows hot stores to simple fields, such as counters or cursors.
  • Linux perf c2c reports many peer hits on one cache line.
  • You measured before and after padding, on the real target hardware.

What We Have Learned

False sharing happens when independent variables share one cache line, so cores keep stealing ownership of that line from each other. In published tests this cost roughly 5 to 8 times in runtime and made timings far less stable. The cure is to keep hot, thread-owned fields on separate lines, using @Contended, array spacing, or LongAdder. However, padding multiplies object size and is not always faster, so profile first, change one thing, and measure again.

Eleftheria Drosopoulou

Eleftheria is an Experienced Business Analyst with a robust background in the computer software industry. Proficient in Computer Software Training, Digital Marketing, HTML Scripting, and Microsoft Office, they bring a wealth of technical skills to the table. Additionally, she has a love for writing articles on various tech subjects, showcasing a talent for translating complex concepts into accessible content.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Back to top button