Scrivio Interview library
CodingIntermediate7 min read · updated 12 November 2026

Two threads each increment their own counter in

Java
class Counters {
volatile long a;
volatile long b;
}

as fast as possible: thread one updates a, thread two updates b. It runs much slower than with one thread. Explain and fix.

The two volatile fields a and b sit in the same 64-byte cache line, so every write by one thread invalidates the line in the other core's cache and the line moves between cores on almost every increment. That is false sharing. We fix it by padding the fields so each has its own cache line, or by using LongAdder, whose cells are already padded with the JDK-internal @Contended annotation, and we confirm the effect with JMH and perf c2c.

Why this question is asked

This is a nice interview problem because the code looks perfectly parallel: each thread has its own counter, there is no lock and no shared variable, so two threads should be about twice as fast as one. Instead they are slower. The answer requires us to stop thinking in Java fields and start thinking in cache lines. In this answer, we will reproduce the slowdown, explain what the hardware is doing, look at three ways to fix it and their trade-offs, and then see how to prove the diagnosis with JMH and perf.

1Reproducing the Slowdown

Here is the class from the question with a small driver. Each thread spins on its own field. The fields are volatile, so every increment is a real store to memory that the JIT cannot keep in a register.

Java
class Counters {
volatile long a;
volatile long b;
}
Counters c = new Counters();
Thread t1 = new Thread(() -> { for (long i = 0; i < 500_000_000L; i++) c.a++; });
Thread t2 = new Thread(() -> { for (long i = 0; i < 500_000_000L; i++) c.b++; });
// Only one thread does c.a++, so the non-atomic ++ is fine here.
// Illustrative timings on a multi-core laptop:
// t1 alone: about 1.0 s
// t1 and t2 together: about 3 to 6 s (much slower, not twice as fast)

The exact numbers vary by CPU, but the pattern is reliable: the second thread makes the first one slower. Something is coupling the two threads even though they never read each other's field.

2Why the Fields Interfere

An object with two long fields is small. With compressed class pointers, the header is 12 bytes, and the two longs follow it, so the whole object is about 32 bytes. It fits easily inside a single 64-byte cache line, and so do a and b.

CPU caches keep data in these lines, and the coherence protocol requires a core to own a line exclusively before writing to it. When thread one on core 1 writes a, core 1 takes the line and invalidates core 2's copy. When thread two on core 2 then writes b, it must fetch the line back from core 1 and invalidate core 1's copy. With both threads writing hundreds of millions of times, the line spends most of its time travelling between the two cores, and each increment waits for that transfer.

So this is false sharing. No data is shared, but the hardware cache line is. The volatile keyword makes it worse because it forces every single increment to be a store the other core must observe, rather than letting the JIT batch updates in a register.

Where the fields land in memory
OffsetContentCache line
0 to 11object headerline 0
16 to 23long a (thread one writes)line 0
24 to 31long b (thread two writes)line 0
32 to 63whatever comes next in the heapline 0
Both hot fields are in one line, so both cores keep stealing it from each other. Exact offsets depend on the JVM.

3Fix 1: Padding the Fields Apart

The idea is to put enough unused bytes between a and b that they land in different lines. There is a subtlety: the JVM is free to reorder fields within one class, so simply declaring seven dummy longs between a and b does not guarantee the layout. A well-known trick is to use class inheritance, because fields of a superclass are laid out before the fields of a subclass.

Java
class PadA { long p01, p02, p03, p04, p05, p06, p07, p08,
p09, p10, p11, p12, p13, p14, p15, p16; } // 128 bytes before a
class FieldA extends PadA { volatile long a; }
class PadB extends FieldA { long q01, q02, q03, q04, q05, q06, q07, q08,
q09, q10, q11, q12, q13, q14, q15, q16; } // 128 bytes between
class Counters extends PadB { volatile long b; }
// Illustrative: t1 and t2 together now take about 1.0 s, the same as one thread

Now a and b are at least 128 bytes apart, so each core keeps its own line and the threads stop interfering. We pad by 128 bytes rather than 64 because some CPUs use 128-byte lines or prefetch adjacent pairs of lines. Libraries such as the LMAX Disruptor and JCTools use this exact pattern. It is ugly, which is why it belongs in a small, well-commented class rather than spread through business code.

4Fix 2: Use LongAdder

If what we really need is a counter that many threads increment, the JDK already solved the problem. LongAdder keeps a base value plus an array of cells. Under contention, threads are spread across different cells, and the cell class is annotated with the JDK-internal @jdk.internal.vm.annotation.Contended annotation, which makes the JVM add padding around it. Reading the total with sum() adds up all the cells.

Java
LongAdder a = new LongAdder();
LongAdder b = new LongAdder();
// thread one: a.increment(); thread two: b.increment();
long total = a.sum(); // sum of base and all cells; not an atomic snapshot

The trade-off is that sum() is more expensive than reading a field and is not an atomic snapshot while updates continue. For statistics and metrics that is exactly right; for a sequence number that must be read precisely after every update, it is not.

5Fix 3: @Contended in Our Own Classes

We can use the same annotation as the JDK, but it is internal. For classes outside the JDK, the JVM ignores it unless we start it with -XX:-RestrictContended, and because the annotation lives in a package that java.base does not export, we must also export that package to our code at compile time and at run time.

Java
import jdk.internal.vm.annotation.Contended;
class Counters {
@Contended volatile long a;
@Contended volatile long b;
}
// javac --add-exports java.base/jdk.internal.vm.annotation=ALL-UNNAMED Counters.java
// java --add-exports java.base/jdk.internal.vm.annotation=ALL-UNNAMED \
// -XX:-RestrictContended -cp . Main

This works, but it depends on an internal API that could change, and it silently does nothing if someone forgets the flag. That is why most teams prefer LongAdder or the inheritance padding pattern.

6Proving the Diagnosis

A guess about cache lines should be confirmed. JMH, the Java microbenchmark harness, makes the comparison reliable: it warms up the JIT, runs several forks and supports thread groups so that two threads can run different methods at once.

Java
@State(Scope.Group)
public class FalseSharingBench {
Counters c = new Counters(); // swap in the padded version to compare
@Benchmark @Group("pair") public void incA() { c.a++; }
@Benchmark @Group("pair") public void incB() { c.b++; }
}
// Unpadded: much lower ops/s per thread; padded: close to the single-thread rate
// On Linux, find the contended line in a running process:
// perf c2c record -p <pid> -- sleep 10
// perf c2c report // shows lines with many cross-core HITM events

perf c2c is especially useful in a real application, because it points at the cache line and the instructions involved, so we can map it back to the Java fields with a tool such as JOL, which prints object layouts.

7Follow-up questions

Why not just make a and b AtomicLong objects?

Two separate AtomicLong objects are allocated one after another and are often adjacent in memory, so they can still share a line. They also use atomic read-modify-write instructions, which are slower than plain volatile stores. Separate objects reduce the chance of false sharing but do not guarantee it.

Would removing volatile fix it?

It would hide it in this benchmark, because the JIT could keep each counter in a register and write it rarely. But then other threads might never see the updates, which is usually not what we want. The layout problem remains for any code that genuinely writes the fields often.

How do you see the field layout of a class?

The JOL tool (Java Object Layout) prints the offsets of every field and the header size for the running JVM. It is the quickest way to confirm whether two hot fields are within 64 bytes of each other.

8Conclusion

In this answer, we saw that two volatile longs in one object share a cache line, so two threads writing them on different cores keep invalidating each other's copy and the line ping-pongs between cores. That is false sharing. We fixed it by padding the fields at least 128 bytes apart with the inheritance pattern, by using LongAdder whose padded cells avoid the issue, or by using @Contended with -XX:-RestrictContended and the package export. Finally, we confirmed the diagnosis with a JMH thread-group benchmark and perf c2c.

What to say in the interviewAbout 90 seconds aloud

Open with

The problem is false sharing. The object is tiny, a header and two longs, so a and b are in the same 64-byte cache line. A core has to own a line exclusively before writing to it, so every time thread one writes a, core 1 takes the line and invalidates core 2's copy, and when thread two writes b, it pulls the line back.

Then, if they want more

The line ping-pongs between the cores on almost every increment, and because the fields are volatile, every increment really is a store the other core must see. So two threads that share no data still slow each other down. To fix it, I would separate the fields into different cache lines.

The robust manual way is padding through class inheritance, because the JVM can reorder fields within a class but lays out superclass fields first, and I would pad by 128 bytes to cover CPUs with larger lines or adjacent-line prefetch. If these are just counters, I would use LongAdder, whose cells are padded with the JDK's internal @Contended annotation.

Using @Contended directly in application code is possible but needs -XX:-RestrictContended and an export of the internal package. I would prove it with a JMH benchmark using thread groups, comparing padded and unpadded layouts, and with perf c2c on Linux.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Two threads each increment their own counter in": https://scrivio-interview-library.netlify.app/java/java-performance/dd5fe4067f/