Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is lock reentrance in java used for? [duplicate]

Possible Duplicate:
What is the Re-entrant lock and concept in general?

I am trying to understand reentrant locks in java and I am looking for a simple explanation. Why is lock reentrance necessary? What problem does it solve? An example scenario would help.

like image 232
vid12 Avatar asked Oct 24 '22 00:10

vid12


1 Answers

A reentrant lock is one that the same thread may acquire more than once. Commonly, a reentrant lock must be unlocked the same number of times that it is locked. A reentrant lock is often much easier to code with. If you have several methods where A calls B and B calls C ... but the client of this code can call into A or B or C, and if you want to lock within each of these methods, then a reentrant lock will solve your problem. It will prevent any thread other than one at a time from accessing this code, but it will allow multiple lock acquisitions so you won't deadlock yourself.

Let's say you have this:

public class SyncTest {
  private final Lock lock = new ReentrantLock();
  public void doA() {
    lock.lock();
    try {
      doB();
      doSomethingForA();
    } finally {
      lock.unlock();
    }
  }

  public void doB() {
    lock.lock();
    try {
      doC();
      doSomethingForB();
    } finally {
      lock.unlock();
    }
  }

  public void doC() {
    lock.lock();
    try {
      doSomeWorkThatEveryoneDoes();
    } finally {
      lock.unlock();
    }
  }
}

where other code can call any of doA or doB or doC and all of them synchronize around some work using the same lock. The lock used is "reentrant" in that the same thread can acquire it multiple times. If the lock were not reentrant, then when you call doA, the moment you enter doB and try to acquire the lock, you will deadlock because the lock is already owned, even though it happens to be owned by yourself.

A pure counting semaphore initialized to a count of one, for example, is a non-reentrant lock. If the same thread tries to acquire it twice, it will block forever in a kind of self-deadlock.

like image 112
Eddie Avatar answered Nov 15 '22 00:11

Eddie