By AmarSivas |
| Updated : 2021-03-12 | Viewed : 8506 times
The reentrant Lock mechanism is one of the techniques to avoid data inconsistency in multi-threaded environments. It is introduced in java 1.5 in the package of java.util.concurrent. It is very useful in multi-threading.
The lock provides access control to thread exclusively on share resources to avoid access control on shared resources by other threads at the same time. A lock is the implementation of the Lock interface which in the package java.util.concurrent.locks.Lock. Synchronization also uses the same type of locking i.e., monitor lock internally to acquired access control on shared resources. But it has its own disadvantages. To overcome these advantages Lock concept is introduced.
Reentrant Lock in Java
Reentrant Lock allows the thread to hold a lock on a particular object. It is mutual lock means the current thread acquires when no other thread acquires the lock. If another thread obtains a lock then the current thread can not obtain the lock until another thread unlocks. in other words, the thread can obtain lock using with lock() method. the lock will be held with the same thread until the method unlock() execution.
lock() method in the ReentrantLock class does acquire the lock on a particular object whereas unlock() method for releasing the lock.
Reentrant Lock same synchronized block i.e., implicit lock. But it provides more extensibility than implicit locks. Reentrant provide fairness where thread preference is the main one for getting the lock.