When should you use LongAdder instead of AtomicLong?
LongAdder internally maintains a base value plus an array of separate cells, using an approach similar to the Striped64 technique, and each thread hashes to one of those cells to perform its increments rather than all threads fighting over a single shared value. Calling sum() adds up the base plus every cell to produce the total. Because different threads are typically writing to different cells, LongAdder scales close to linearly under high contention, whereas AtomicLong forces every incrementing thread to compete for compare-and-swap on the exact same memory location, which degrades badly as contention rises. The practical rule is to use LongAdder when many threads are incrementing frequently and you only need to read the total occasionally, such as for metrics collection or request counters, and to use AtomicLong when you need operations like compareAndSet(), need the precise current value at any moment, or expect only moderate contention.
Ready to master this question?
Generate a complete walkthrough — background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.
Sign in to generate a response