Working with Locks and Atomic Variables

1. Using ReentrantLock

APIUse
lock() / unlock()Manual locking
lockInterruptibly()Interruptible wait
tryLock([t, u])Non-blocking / timed
new ReentrantLock(true)Fair mode
newCondition()Condition variable

Example: try/finally pattern

lock.lock();
try { criticalSection(); }
finally { lock.unlock(); }

2. Using ReadWriteLock

LockAllows
readLockMultiple concurrent readers
writeLockExclusive (no readers, no writers)
DowngradeWrite → read OK
UpgradeRead → write FORBIDDEN (deadlock)

3. Using StampedLock

ModeUse
writeLockExclusive, returns stamp
readLockShared, returns stamp
tryOptimisticReadLock-free; validate with validate(stamp)
NotReentrant; not Condition-friendly

4. Understanding Lock Fairness

ModeBehavior
Non-fair (default)Higher throughput; possible starvation
FairFIFO; lower throughput, predictable
RuleUse fair only when starvation observed

5. Using Condition Variables

APIUse
cond.await()Release lock, wait, re-acquire
cond.signal / signalAllWake waiters
Multiple conditionsOne per logical state (notFull, notEmpty)

6. Using AtomicInteger and AtomicLong

MethodEffect
get / setVolatile
incrementAndGet / decrementAndGetAtomic +/- 1
addAndGet(delta)Atomic +delta
compareAndSet(exp, new)CAS
updateAndGet(unaryOp)CAS-loop with function

7. Using AtomicReference (object atomicity)

MethodUse
compareAndSet(exp, new)Identity-based CAS
updateAndGet(fn)Functional update
ABAUse AtomicStampedReference

8. Using AtomicBoolean

UsePattern
Init guardif (started.compareAndSet(false, true))
Cancel flagSet true; check in loop

9. Understanding Compare-And-Swap (CAS)

ConceptDetail
Atomic opHW instruction (cmpxchg)
PatternRead-Modify-Write loop until success
ProsLock-free, no context switch
ConsContention causes retries

10. Using LongAdder and LongAccumulator

ClassUse
LongAdderHigh-contention counters; cells per thread
LongAccumulatorGeneralized: any binary op + identity
vs AtomicLongBetter under contention; sum() is approximate snapshot

11. Avoiding Deadlocks

StrategyDetail
Lock orderingGlobal order all threads follow
tryLock + back-offAvoid hold-and-wait
TimeoutDetect potential deadlock
Reduce scopeHold locks briefly
ThreadMXBeanDetect at runtime: findDeadlockedThreads()

12. Using Lock-Free Algorithms

PatternBuilding Block
CounterLongAdder
StackTreiber stack via AtomicReference
QueueMichael-Scott (ConcurrentLinkedQueue)
MapConcurrentHashMap (locked bins)