Java
Reentrant Lock in Java:
A reference to explicit locking, fairness, timed acquisition, and conditions with ReentrantLock.
1 view
- Reentrant: Thread can reacquire lock, incrementing hold count.
- Explicit Lock/Unlock: Uses
lock()andunlock(), typically in try-finally. - Fairness: Optional fair mode (
new ReentrantLock(true)) reduces starvation. - TryLock: Non-blocking
tryLock()or timedtryLock(long, TimeUnit). - Conditions: Supports multiple
Conditionobjects for thread coordination. - Interruptible:
lockInterruptibly()allows interruption during lock wait. - Hold Count: Tracks reentrant acquisitions with
getHoldCount(). - Ownership: Checks lock owner (
getOwner()) or current thread (isHeldByCurrentThread()). - Queue Info: Inspects waiting threads with
getQueueLength()orgetWaitingThreads(). - Flexible Scope: Lock/unlock not bound to block scope.
- High Performance: Often outperforms
synchronizedin contention. - No Deadlock Prevention: Requires careful use to avoid deadlocks.