How many of you still need to use (for non-ownership lock release) or have a code base which uses semaphores (shorturl.at/fjzPW) ? At least, I have not seen a code base in last 8+ years with semaphores in it. Based on my discussion with few fresh dev interview candidates in the past , I thought it might be a good idea to share some light on the term reentrant locks. The word itself is self explanatory. A lock which can be entered again or acquired again. The only conditions is - "by the same thread". Can be better described with a code example
private Lock lock = new ReentrantLock(true);
private void lockMyselfWithoutDeadLock(int counter){
if (counter <= 0){
return;
}
lock.lock();
System.out.println("Call Myself");
lockMyselfWithoutDeadLock(counter-1);
lock.unlock();
}
public static void main(String[] args){
ReEntrantLock reEntrantLock = new ReEntrantLock();
reEntrantLock.lockMyselfWithoutDeadLock(5);
}
Any thread which calls above method with a positive number and is able to acquire lock once, will be able to call itself, until returned and thus re-acquiring the lock multiple times.
TO explain a non-reentrant lock,I would use an example of Semaphore. Think of it like a ticketed entry point which can allow a certain number of permits. A thread which has a valid permit can use that permit once to enter. If a thread can get one more permit, it can enter the lock one more time. Main point is that there is a limit. Its not like re-entrant locks where same thread can gain the lock any number of times. Following example will showcase the scenario
private Semaphore lock = new Semaphore(2); // 2 Permits
private void lockMyselfWithDeadLock(int counter) throws
InterruptedException
{
if (counter <= 0){
return;
}
lock.acquire();
System.out.println("Call Myself");
lockMyselfWithDeadLock(counter-1);
lock.release();
}
public static void main(String[] args) throws InterruptedException {
NonReEntrantLock nonReEntrantLock = new NonReEntrantLock();
nonReEntrantLock.lockMyselfWithDeadLock(5);
}
The above program will be in a deadlock if called with an argument greater than 2 as semaphore holds only 2 permits. I hope this will help someone trying to learn concurrency !!
Top comments (2)
I think the synchronized keyword also works like a reentrant lock.
Yes, synchronized blocks are reentrant too !