![]() |
VOOZH | about |
In Java, a Reentrant Lock is part of the java.util.concurrent.locks package and provides a more flexible mechanism for thread synchronization compared to the synchronized keyword. It allows threads to enter a lock multiple times (reentrant behavior) without causing deadlock on itself. It offers features like:
Reentrant locks are created using the ReentrantLock class:
Inside Method A Inside Method B
Here, the same thread acquires the lock twice without any issue, demonstrating reentrant behavior.
Reentrant locks can be created with a fairness option:
| Method | Description |
|---|---|
| lock() | Acquires the lock, incrementing the hold count. If the resource is free, the current thread gets it. |
| unlock() | Releases the lock, decrementing the hold count. When the count reaches zero, the resource is released. |
| tryLock() | Attempts to acquire the lock without blocking. Returns true if successful, false if busy. |
| tryLock(long timeout, TimeUnit unit) | Waits up to the specified time to acquire the lock, then exits if unsuccessful. |
| lockInterruptibly() | Acquires the lock unless the thread is interrupted while waiting. |
| getHoldCount() | Returns the number of times the current thread holds the lock. |
| isHeldByCurrentThread() | Returns true if the current thread holds the lock. |
| hasQueuedThreads() | Checks if there are threads waiting to acquire the lock. |
| isLocked() | Returns true if any thread holds the lock. |
| newCondition() | Returns a Condition instance associated with this lock for advanced thread coordination. |
| Feature | synchronized | ReentrantLock |
|---|---|---|
| Lock acquisition | Implicit | Explicit (lock() and unlock()) |
| Interruptible | No | Yes |
| Try-lock | No | Yes (tryLock()) |
| Fairness | No | Optional |
| Reentrant | Yes | Yes |