Reentrant Lock in Java

Reentrant lock in Java is the implementation class of the Lock interface. Reentrant means a thread can acquire the same lock multiple times without any issue. internally reentrant lock increment thread’s count whenever we call the lock method and decrement count value whenever the thread call unlocks method. The lock will release whenever the count value becomes zero.


 ReentrantLock rlock = new ReentrantLock();

This constructor creates an instance of a reentrant lock.

 ReentrantLock rlock = ReentrantLock(boolean fair )

This constructor is used to create a reentrant lock with a given fair policy. if the fair value is true then the longest waiting thread can acquire the lock if it is available i.e., it follows a first come first serve policy. If the fair value is false which thread will get the chance we can not expect?

Note- The default value of fair is false.

Important Method of ReentrantLock

int getHoldCount()

This method returns the number of holds on this lock by the current thread.

boolean isHeldByCurrentThread()

This method returns true if and only if the lock is held by the current thread.

int getQueueLength()

This method returns a number of threads waiting for the lock.

boolean hasQueuedThread( Thread thread )

This method returns true if any thread waiting to get the lock.

boolean isLocked()

This method returns true if the lock is acquired by any thread.

boolean isFair()

This method returns true if fair policy is set to true.

Similar Java Tutorials

2 thoughts on “Reentrant Lock in Java”

Leave a Comment