Locksmedium3-5 years

How does AtomicInteger work without a lock, and when does LongAdder win?

Compare-and-swap: read the value, compute the new one, write it only if the value is still what you read; on failure, retry with the fresh value. One CPU instruction, no parking. Under heavy contention many threads spin on the same cache line — LongAdder spreads increments across cells and sums on read, so it wins for write-heavy counters.

The lesson behind it →
More on Locks