Extrinsic locks in JAVA
Locks are a mechanism to restrict multiple threads accessing a shared resource (“critical section”). Lock facilitates an exclusive access to the shared resource and it can be acquired by one thread at a time. Locks act as a gateway to access the shared resource, so in order to access the shared resource the thread accessing it must posses the lock.
Java dedicates a complete package(java.util.concurrent.locks) for extrinsic locks. Let’s explore how these locks work under the hood. There are few pre requisite needed to go further.
a. Thread.
b. Synchronization.
A basic understanding of the above two topics will suffice to go through the article further.
An extrinsic lock in java must implement the java.util.concurrent.locks.Lock interface.
To add further a lock can be shared with multiple threads as well, if the implementation of the Lock interface permits it. So a lock can be Exclusive or Shared.Typically a shared lock can be used while reading (read lock) a shared resource(“critical section”).
Let’s have a brief overview of the methods in the lock interface.
Get sam rubin’s stories in your inbox
Join Medium for free to get updates from this writer.
lock(): In order to acquire a lock, a thread must invoke the lock() method on the Lock Object (For Instance :Reentrant lock ) and success for acquisition depends upon the following scenario.
In Case of a Reentrant lock, a thread can successfully acquire a lock, if the lock is not yet acquired by other thread or the thread trying to acquire the lock already holds it (Reentrant scenario). If both the scenario fails then the thread will be blocked / dormant until it gets the lock.
lockInterruptibly() : It is similar to lock method, additionally it supports interruption. Whenever an interrupt() method is invoked on this thread then it will exit the “critical section” if it has already acquired the lock. If not, it will be in the AQS(AbstractQueuedSynchronizer) queue and the status bit of the node will be set to cancelled. We will have a separate article for AQS in this series.
tryLock(): This method will return true, if the lock is available and acquires it, if not it returns false immediately. tryLock() method will not block the thread unlike lock() method.
tryLock(long,TimeUnit): It is overloaded method of tryLock() method with an extended capability to wait for the specified time(argument).
unlock() : This method releases the lock acquired via lock() method.
newCondition(): This method returns an instance of Condition object, a condition object makes the thread to be suspend on invoking the await() method and it will be released on invoking the signal()/signalAll() method.
Let’s explore about the implementations of lock interface and how they work internally with the help of Reentrant lock.
Reference : Openjdk 17







