Working with Locks and Atomic Variables
1. Using ReentrantLock
| API | Use |
|---|---|
lock() / unlock() | Manual locking |
lockInterruptibly() | Interruptible wait |
tryLock([t, u]) | Non-blocking / timed |
new ReentrantLock(true) | Fair mode |
newCondition() | Condition variable |
2. Using ReadWriteLock
| Lock | Allows |
|---|---|
| readLock | Multiple concurrent readers |
| writeLock | Exclusive (no readers, no writers) |
| Downgrade | Write → read OK |
| Upgrade | Read → write FORBIDDEN (deadlock) |
3. Using StampedLock
| Mode | Use |
|---|---|
writeLock | Exclusive, returns stamp |
readLock | Shared, returns stamp |
tryOptimisticRead | Lock-free; validate with validate(stamp) |
| Not | Reentrant; not Condition-friendly |
4. Understanding Lock Fairness
| Mode | Behavior |
|---|---|
| Non-fair (default) | Higher throughput; possible starvation |
| Fair | FIFO; lower throughput, predictable |
| Rule | Use fair only when starvation observed |
5. Using Condition Variables
| API | Use |
|---|---|
cond.await() | Release lock, wait, re-acquire |
cond.signal / signalAll | Wake waiters |
| Multiple conditions | One per logical state (notFull, notEmpty) |
6. Using AtomicInteger and AtomicLong
| Method | Effect |
|---|---|
get / set | Volatile |
incrementAndGet / decrementAndGet | Atomic +/- 1 |
addAndGet(delta) | Atomic +delta |
compareAndSet(exp, new) | CAS |
updateAndGet(unaryOp) | CAS-loop with function |
7. Using AtomicReference (object atomicity)
| Method | Use |
|---|---|
compareAndSet(exp, new) | Identity-based CAS |
updateAndGet(fn) | Functional update |
| ABA | Use AtomicStampedReference |
8. Using AtomicBoolean
| Use | Pattern |
|---|---|
| Init guard | if (started.compareAndSet(false, true)) |
| Cancel flag | Set true; check in loop |
9. Understanding Compare-And-Swap (CAS)
| Concept | Detail |
|---|---|
| Atomic op | HW instruction (cmpxchg) |
| Pattern | Read-Modify-Write loop until success |
| Pros | Lock-free, no context switch |
| Cons | Contention causes retries |
10. Using LongAdder and LongAccumulator
| Class | Use |
|---|---|
| LongAdder | High-contention counters; cells per thread |
| LongAccumulator | Generalized: any binary op + identity |
| vs AtomicLong | Better under contention; sum() is approximate snapshot |
11. Avoiding Deadlocks
| Strategy | Detail |
|---|---|
| Lock ordering | Global order all threads follow |
tryLock + back-off | Avoid hold-and-wait |
| Timeout | Detect potential deadlock |
| Reduce scope | Hold locks briefly |
| ThreadMXBean | Detect at runtime: findDeadlockedThreads() |
12. Using Lock-Free Algorithms
| Pattern | Building Block |
|---|---|
| Counter | LongAdder |
| Stack | Treiber stack via AtomicReference |
| Queue | Michael-Scott (ConcurrentLinkedQueue) |
| Map | ConcurrentHashMap (locked bins) |