Java Reentrant Lock

ReentrantLock implements the lock interface to provide Mutual Exclusion. It uses the bridge pattern.

It inherits functionality from the AbstractQueuedSynchronizer class which provides a framework for implementing blocking locks and synchronizers that rely on First In, First Out or FIFO wait queues.

It implements several lock acquisition models via its common interface. It optionally implements fair or non-fair lock acquisition model. If the fair paraameter pass, so the ReentrantLock instructor is true, then access is always granted to the longest waiting thread. However if it is false or if the default constructor is used, a lock does not guarantee any particular access order.



Key methods are lock, lockInterruptibly and unlock.
Lock acquires a lock if its available otherwise it spins or blocks until the lock becomes available.
LockInterruptibly acquires the lock unless thread is interrupted, in which case it throws an interrupted exception.
Unlock attempts to release the lock if its the holder

These methods simply forward to their fair implementations or non-fair implementations selected in the ReentrantLock instructor.

Non fair implementations are optimized to use faster mutual exclusion mechanism such as spin locks.

In summary a Java ReentrantLock provides a lightweight mutual exclusion mechanism that defines a critical section where only one thread at a time can execute. It provides the same basic behavior and semantics as the implicit monitor lock accessed using Java's built in synchronized methods are statements, but with extended capabilities such as methods that perform non-blocking interruptible and time lock acquisition operations.

A ReentrantLock must be used by a fully bracketed protocol, since a thread that acquires a lock must be the one to release it.

A thread owning a ReentrantLock can reacquire it without deadlocking since the underlying ReentrantLock implementation simply increments its hold count in accordance with the recursive lock semantics.

Although ReentrantLocks are a fundamental mutual exclusion mechanism, they can be tedious and error-prone to program due to the following common mistakes.

  • Acquiring a lock and forgetting to release it
  • Releasing a lock that was never acquired
  • Holding a lock for a long time without needing it
  • Accessing a resource without acquiring a lock for it first(or after releasing it)
Java built-in monitor objects addresses some of these limitations.

0 comments: