Scrivio Interview library
ScenarioIntermediate7 min read · updated 12 November 2026

A global sequence generator uses AtomicLong.incrementAndGet and is called by 64 threads at very high rates. Profiling shows CPU time in the increment. Explain the cost and options.

With 64 threads calling incrementAndGet on one AtomicLong, every increment needs exclusive ownership of the same cache line, so the line bounces between cores and each increment waits for the previous one to finish somewhere else. If we only need a total count, LongAdder spreads updates over several cells and removes the contention. If we need unique ids, each thread can take a block of ids from the AtomicLong at once, or we can drop strict global ordering and use time-based or per-node id schemes. Whatever we choose, we verify the gain with JMH at realistic thread counts.

Why this question is asked

An AtomicLong counter looks as cheap as code can get: one method call, no locks. So it surprises people when a profiler shows a noticeable share of CPU time in incrementAndGet. Interviewers ask this scenario because the explanation is in the hardware, not in Java, and because the right fix depends on what the number is used for. In this answer, we will see why one shared counter is expensive, separate the two jobs a counter can do, fix each one with a fitting tool, look at id schemes that need no shared counter, and finish with how to measure the improvement properly.

1Why One Counter Becomes a Hot Spot

Each CPU core has its own cache, and memory moves between caches in blocks of 64 bytes called cache lines. To write a variable, a core must own its cache line exclusively; every other core's copy is invalidated. On x86, incrementAndGet compiles to a single lock xadd instruction, which never retries, but it still needs that exclusive ownership.

Now 64 threads on 64 cores increment the same AtomicLong. Core 1 takes the line and increments. Core 2 requests the line, waits for it to travel from core 1, increments, and so on. The increments are serialized, one at a time, and each one includes a transfer between cores that costs on the order of 50 to 200 nanoseconds, more if the cores are on different sockets. So throughput across the whole machine is capped at roughly 5 to 20 million increments per second, and adding threads makes each thread slower rather than adding capacity. The profiler shows this time as CPU spent in the increment, because the core is stalled waiting for the line.

Step throughOne cache line, many cores
Core 1Core 2Core 3Cache line of counter
take line exclusively, add 1
request line
line moves from core 1
add 1
request line
line moves from core 2
add 1
request line again

8 messages in order. Play them, or step through them one at a time.

Every increment waits for the line to arrive from the last writer, so the counter is a serial bottleneck.

2First Ask What the Number Is For

A counter can serve two quite different purposes. Sometimes we only need the total, for example how many events we processed, and nobody cares about the order of individual increments. Other times each caller needs its own unique value, for example an id for an order or a sequence number in a log. The fixes differ, so this is the first question to ask the team.

There is a related third question: if the values are ids, do they really need to be strictly sequential across the whole service, with no gaps and in exact order? Usually the honest answer is that they need to be unique and roughly increasing, which opens up much cheaper designs.

3Fix 1: LongAdder for Totals

LongAdder keeps a base value plus an array of cells, each on its own cache line. When threads contend, each thread is steered to a different cell and increments only that, so cores stop fighting over one line. sum() adds the base and all cells when someone asks for the total.

Java
LongAdder processed = new LongAdder();
// hot path, 64 threads
processed.increment(); // usually touches only this thread's cell
// metrics scrape every 15 seconds
long total = processed.sum(); // base + all cells, for example 1_284_330_112

The catch is that a LongAdder cannot hand out unique values. There is no incrementAndGet that returns a meaningful number, and sum() is not an atomic snapshot while updates continue. It is ideal for statistics and useless as an id generator.

4Fix 2: Hand Out Ids in Blocks

If each caller needs a unique id, we can keep the AtomicLong but touch it far less often. Each thread reserves a block of, say, 1,000 ids with one addAndGet, then hands them out from a plain local counter. The shared variable is now updated once per thousand ids, so contention drops by that factor.

Java
final class BlockIdGenerator {
private static final int BLOCK = 1_000;
private final AtomicLong next = new AtomicLong();
private final ThreadLocal<long[]> range = ThreadLocal.withInitial(() -> new long[] {0, 0});
long nextId() {
long[] r = range.get(); // r[0] = next id, r[1] = end of block
if (r[0] == r[1]) {
long end = next.addAndGet(BLOCK); // one shared update per 1,000 ids
r[0] = end - BLOCK;
r[1] = end;
}
return r[0]++; // thread A: 0, 1, 2 ... thread B: 1000, 1001 ...
}
}

Notice what we gave up: ids are unique but no longer in global order of creation. Thread B may issue 1000 before thread A issues 5. If a thread or the service stops, the rest of its block is never used, leaving gaps. Databases make the same trade-off: a PostgreSQL sequence with CACHE 1000 or Hibernate's pooled optimizer reserves ranges in exactly this way. With virtual threads, which can number in the millions, a ThreadLocal per thread is a poor fit, so we would keep one block per carrier, per shard or per worker instead.

5Ids Without a Shared Counter

Often the strict sequence was never a requirement. Time-based schemes build ids without any shared state between threads or even between machines. A Snowflake-style id packs a millisecond timestamp, a node number and a small per-node sequence into one long, so ids are unique across a cluster and roughly ordered by time. UUID version 7, defined in RFC 9562, puts a Unix millisecond timestamp in its first 48 bits followed by random bits, which makes it sortable and friendly to database indexes. The JDK up to Java 25 offers UUID.randomUUID() (version 4) but no version 7 generator, so we would use a small library or our own code for that; check your version.

These designs move the decision from 'how do we make the counter faster' to 'do we need one counter at all', which is usually the bigger win.

Options for a hot counter
NeedToolTrade-off
Total count onlyLongAdderNo unique values; sum() approximate
Unique ids, one JVMBlocks from an AtomicLongNot globally ordered; gaps
Unique ids, many nodesSnowflake-style or UUIDv7Roughly ordered; needs node id or more bits
Strict gapless sequenceOne AtomicLong or DB sequenceSerial bottleneck by design

6Measuring the Improvement With JMH

Concurrent performance cannot be judged by intuition or by a loop with System.nanoTime(). JMH, the Java Microbenchmark Harness, handles warm-up, dead-code elimination and thread coordination. We benchmark each option with the thread counts we really run, for example @Threads(1), @Threads(16) and @Threads(64), on the same hardware as production, because the cost of cache line transfers differs greatly between a laptop and a two-socket server.

Java
@State(Scope.Benchmark)
public class CounterBench {
final AtomicLong atomic = new AtomicLong();
final LongAdder adder = new LongAdder();
@Benchmark @Threads(64) public long atomic() { return atomic.incrementAndGet(); }
@Benchmark @Threads(64) public void adder() { adder.increment(); }
}

On a many-core server it is common for the LongAdder version to be an order of magnitude faster at 64 threads while being slightly slower at one thread. The exact numbers depend on the machine, which is precisely why we measure, and why we confirm afterwards in the service's own profile that the hot spot is gone.

7Follow-up questions

Would making the counter volatile long with synchronized help?

No, it would be worse. synchronized adds lock acquisition on top of the same cache line traffic, and under contention threads block. The bottleneck is the single shared memory location, not the atomic instruction.

Does false sharing play a role here?

It can make things worse. If the AtomicLong sits on the same cache line as other frequently written fields, those writes also bounce the line. LongAdder's cells are padded with @Contended to avoid exactly this; our own hot fields may need the same care.

Why is LongAdder slower with one thread?

With no contention it updates only the base field with a CAS, which costs about the same as AtomicLong plus a little bookkeeping. The cells are created only after contention is detected, so the overhead is small, but sum() is always a little more work than get().

8Conclusion

In this answer, we saw that a single AtomicLong under 64 threads serializes every increment through one cache line that moves from core to core, which is the CPU time the profiler showed. For totals, LongAdder spreads the work across cells; for unique ids, reserving blocks from the AtomicLong cuts shared updates by the block size; and when strict ordering is not required, time-based schemes such as Snowflake-style ids or UUIDv7 need no shared counter at all. We confirm any change with JMH at realistic thread counts on production-like hardware.

What to say in the interviewAbout 90 seconds aloud

Open with

The cost isn't the instruction itself, it's the cache line. To increment, a core needs exclusive ownership of the line holding the AtomicLong, so with 64 threads the line bounces from core to core and the increments are effectively serialized, each one waiting for a cross-core transfer of maybe a hundred nanoseconds.

Then, if they want more

That shows up as CPU time in incrementAndGet, and adding threads just makes each one slower. The fix depends on what the number is for. If it's just a total, like events processed, I'd switch to LongAdder, which gives contended threads separate padded cells and only adds them up in sum.

If callers need unique ids, I'd keep the AtomicLong but have each thread or worker reserve a block, say a thousand ids with one addAndGet, and hand them out locally, so the shared variable is touched a thousand times less often. That gives up global ordering and leaves gaps, which is the same trade-off a cached database sequence makes.

And I'd ask whether ids really need to be strictly sequential; usually unique and roughly time-ordered is enough, and then a Snowflake-style id or a UUIDv7 avoids a shared counter entirely. Whatever we pick, I'd prove it with a JMH benchmark at 1, 16 and 64 threads on production-like hardware, and then check the service profile again.

About this answer

Last updated
12 November 2026
Versions it names
Java 25
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 "A global sequence generator uses AtomicLong.incrementAndGet and is called by 64 threads...": https://scrivio-interview-library.netlify.app/java/atomics/8c83176da7/