Why is LongAdder more efficient than AtomicLong under high contention? Under what conditions does LongAdder work effectively?
sobes.tech AI
Answer from AI
LongAdder is more efficient than AtomicLong under high contention due to its internal architecture, which reduces contention for a single shared counter.
AtomicLong uses atomic CAS (compare-and-swap) operations on a single value, which can lead to frequent conflicts and retries when many threads are involved.
LongAdder, on the other hand, splits the counter into multiple cells, each of which can be updated independently by a thread or a group of threads. The total value is obtained by summing all the cells.
Conditions for effective use of LongAdder:
- High contention during counter updates (many threads simultaneously).
- Frequent increment/decrement operations.
In cases of low contention or when precise atomic read/write operations are required, AtomicLong may be preferable.
Example of using LongAdder:
import java.util.concurrent.atomic.LongAdder;
LongAdder counter = new LongAdder();
// In different threads
counter.increment();
// Getting the total value
long total = counter.sum();
Thus, LongAdder improves performance in multi-threaded scenarios by reducing conflicts during counter updates.