Understanding AtomicLong vs LongAdder in Java Concurrency
In high‑concurrency Java applications, LongAdder—introduced in JDK 8 and using partitioned cells to reduce contention—generally outperforms the single‑value AtomicLong, which relies on CAS and can cause CPU waste under heavy load, so Alibaba advises LongAdder for scalable distributed counters, though memory usage and workload specifics must be considered.
In distributed systems a counter is a common requirement. To achieve high concurrency and high availability, choosing the right implementation is crucial.
Java provides two typical counter implementations: AtomicLong and LongAdder . Alibaba’s technical report recommends LongAdder over AtomicLong.
CAS (compare‑and‑swap) is the atomic primitive behind both classes. It compares the current value with the memory value and, if they match, updates it. The classic ABA problem can occur when a value changes from A to B and back to A, misleading a CAS operation.
Java solves ABA with AtomicStampedReference , which adds a version stamp to the value.
LongAdder was introduced in JDK 8 by Doug Lea. It partitions a long value into multiple cells, each updated by a separate thread, reducing contention. This design yields higher throughput in high‑concurrency scenarios at the cost of extra memory.
AtomicLong uses a single value and CAS for each update. Under heavy contention many threads spin and retry, leading to CPU waste.
Consequently, Alibaba recommends LongAdder for high‑concurrency distributed systems because of its better performance, scalability, and suitability for large‑scale request handling.
In practice, choose the implementation based on the specific workload and memory constraints.
Java Tech Enthusiast
Sharing computer programming language knowledge, focusing on Java fundamentals, data structures, related tools, Spring Cloud, IntelliJ IDEA... Book giveaways, red‑packet rewards and other perks await!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.