Loading…
Loading…
84 карточек
Why is LongAdder often faster than AtomicLong in highly concurrent scenarios?
нажми, чтобы перевернуть
LongAdder uses striping (splitting into cells) to reduce contention, summing values only on read. AtomicLong relies on CAS, which causes spin loops under conflicts.AtomicLong uses Unsafe.compareAndSwapLong(). Under high contention, many threads try to update a single memory cell. CAS fails, the thread retries (spins), wasting CPU and causing cache-line bouncing. LongAdder creates an array of cells (Cell[]). Each thread hashes to its own cell, updating it locally without CAS conflicts. The sum() method aggregates all cells. This provides near-linear scaling on multi-core CPUs.
Tradeoff:
LongAdderconsumes more memory (cell array) and does not guarantee instantaneous value consistency.sum()offers eventual consistency.
Use AtomicLong for low-contention counters or when exact atomicity per step is required. LongAdder — for metrics, statistics, and log aggregation in high-load systems.
Когда да
For metric aggregation, counting requests/errors in high-load services (10k+ RPS), where throughput matters more than instantaneous accuracy.
Когда нет
For financial transactions, unique ID generators, or when an exact value is required after every operation.
Совет на собеседовании
Explain how cache-line bouncing works and why CAS becomes expensive with >4 cores.
Свайп вправо — знаю, влево — не знаю
