Guard the Counter With a Mutex (ReentrantLock) Versus Use a Lock-Free AtomicLong With CAS
TradeoffConcurrencySeniorStaffUpdated
A hot counter is hit by 64 threads thousands of times per second. You need correctness without crushing throughput.
Short answer: Use a lock-free AtomicLong with CAS. For single-word updates, CAS avoids the syscall and context-switch cost of mutex contention and scales linearly with CPU count up to the point where CAS retries dominate.
The Two Options
A
Guard the counter with a mutex (ReentrantLock)
B
Use a lock-free AtomicLong with CAS
Drill This: Your Pick First
The Better Pick
Option B
Use a lock-free AtomicLong with CAS
For single-word updates, CAS avoids the syscall and context-switch cost of mutex contention and scales linearly with CPU count up to the point where CAS retries dominate. Mutexes win once the critical section grows to multiple statements.
When the Other One Wins
Guard the counter with a mutex (ReentrantLock)
If the critical section is several reads and writes that must be atomic together, a mutex is simpler and faster than a hand-rolled CAS loop.