What is the meaning of "ReentrantLock" in Java?
Asked Answered
B

6

50

Reentrancy means that locks are acquired on a per-thread rather than per-invocation basis.

Since an intrinsic lock is held by a thread, doesn't it mean that a thread run once equals an invocation basis?

Thank you, it seems mean that: in a thread,if I get a lock lockA when process function doA which call function doB, and doB also need a lock lockA,then there wil be a reentrancy. In Java, this phenomenon is acquired per thread, so I needn't consider deadlocks?

Brigettebrigg answered 12/5, 2013 at 4:34 Comment(4)
Imagine if entering a method locks object X, and while in that method you call the very same method (either directly or further on in the call stack) and lock object X again. What happens? Do you wait on the lock you already hold, or is it aware that the thread holding it is also the thread calling it again, and allows it to pass? This is called re-entrancy - you enter the same method you were already in earlier.Aerostation
Yes, synchronized blocks and locks in Java are re-entrant, so once thread foo has lock bar, it can safely call methods that also lock bar without having to unlock it first.Aerostation
You still must consider deadlock, deadlock can occur when two threads wait on each other.Armoire
yeal, I mean my situation above.Brigettebrigg
W
79

Reentrancy means that locks are acquired on a per-thread rather than per-invocation basis.

That is a misleading definition. It is true (sort of), but it misses the real point.

Reentrancy means (in general CS / IT terminology) that you do something, and while you are still doing it, you do it again. In the case of locks it means you do something like this on a single thread:

  1. Acquire a lock on "foo".
  2. Do something
  3. Acquire a lock on "foo". Note that we haven't released the lock that we previously acquired.
  4. ...
  5. Release lock on "foo"
  6. ...
  7. Release lock on "foo"

With a reentrant lock / locking mechanism, the attempt to acquire the same lock will succeed, and will increment an internal counter belonging to the lock. The lock will only be released when the current holder of the lock has released it twice.

Here's a example in Java using primitive object locks / monitors ... which are reentrant:

Object lock = new Object();
...
synchronized (lock) {
    ...
    doSomething(lock, ...)
    ...
}

public void doSomething(Object lock, ...) {
    synchronized (lock) {
        ...
    }
}

The alternative to reentrant is non-reentrant locking, where it would be an error for a thread to attempt to acquire a lock that it already holds.

The advantage of using reentrant locks is that you don't have to worry about the possibility of failing due to accidentally acquiring a lock that you already hold. The downside is that you can't assume that nothing you call will change the state of the variables that the lock is designed to protect. However, that's not usually a problem. Locks are generally used to protect against concurrent state changes made by other threads.


So I needn't consider deadlocks?

Yes you do.

A thread won't deadlock against itself (if the lock is reentrant). However, you could get a deadlock if there are other threads that might have a lock on the object you are trying to lock.

Wellworn answered 12/5, 2013 at 4:40 Comment(0)
A
23

Imagine something like this:

function A():
   lock (X)
       B()
   unlock (X)

function B():
    A()

Now we call A. The following happens:

  • We enter A, locking X
  • We enter B
  • We enter A again, locking X again

Since we never exited the first invocation of A, X is still locked. This is called re-entrance - while function A has not yet returned, function A is called again. If A relies on some global, static state, this can cause a 're-entrance bug', where before the static state is cleaned up from the function's exit, the function is run again, and the half computed values collide with the start of the second call.

In this case, we run into a lock we are already holding. If the lock is re-entrance aware, it will realize we are the same thread holding the lock already and let us through. Otherwise, it will deadlock forever - it will be waiting for a lock it already holds.

In java, lock and synchronized are re-entrance aware - if a lock is held by a thread, and the thread tries to re-acquire the same lock, it is allowed. So if we wrote the above pseudocode in Java, it would not deadlock.

Aerostation answered 12/5, 2013 at 4:47 Comment(0)
C
15

Java concurrency in practice book states - Reentrancy means that locks are acquired on a per-thread rather than per-invocation basis.

Let me explain what it exactly means. First of all Intrinsic locks are reentrant by nature. The way reentrancy is achieved is by maintaining a counter for number of locks acquired and owner of the lock. If the count is 0 and no owner is associated to it, means lock is not held by any thread. When a thread acquires the lock, JVM records the owner and sets the counter to 1.If same thread tries to acquire the lock again, the counter is incremented. And when the owning thread exits synchronized block, the counter is decremented. When count reaches 0 again, lock is released.

A simple example would be -

public class Test {
    public synchronized void performTest() {
       //...
    }
}

public class CustomTest extends Test {
    public synchronized void performTest() {
       //...
       super.performTest();
    }
}

without reentrancy there would be a deadlock.

enter image description here

Crackling answered 7/6, 2016 at 4:1 Comment(0)
E
4

Reentrancy means that locks are acquired on a per-thread rather than per-invocation basis.

Let me explain this with an example.

class ReentrantTester {

    public synchronized void methodA() {
      System.out.println("Now I am inside methodA()");
      methodB();
    }

    public synchronized void methodB() {
      System.out.println("Now I am inside methodB()");
    }

    public static void main(String [] args) {
        ReentrantTester rt = new ReentrantTester();
        rt.methodA();  
    }

}

The out put is :

Now I am inside methodA()
Now I am inside methodB()

As in the above code, the ReentrantTester contains two synchronized methods: methodA() & methodB() The first synchronized method methodA() calls the other synchronized method methodB().

When execution enters the methodA(), the current thread acquires the monitor for the ReentrantTester object. Now when methodA() calls methodB(), because methodB() is also synchronized, the thread attempts to acquire the same monitor again. Because Java supports reentrant monitors, this works. The current thread acquire the ReentrantTester's monitor again and continue the execution of both methodA() and methodB().

The Java runtime allows a thread to reacquire a monitor that it already holds, because Java monitors are reentrant. These reentrant monitors are important because they eliminate the possibility of a single thread deadlocking itself on a monitor that it already holds.

Edna answered 10/2, 2019 at 6:18 Comment(0)
A
2

This just means once a thread has a lock it may enter the locked section of code as many times as it needs to. So if you have a synchronized section of code such as a method, only the thread which attained the lock can call that method, but can call that method as many times as it wants, including any other code held by the same lock. This is important if you have one method that calls another method, and both are synchronized by the same lock. If this wasn't the case the. The second method call would block. It would also apply to recursive method calls.

public void methodA()
{
     // other code
     synchronized(this)
     {
          methodB();
     } 
}

public void methodB()
{
     // other code
     syncrhonized(this)
     {
          // it can still enter this code    
     }

}
Armoire answered 12/5, 2013 at 4:37 Comment(0)
C
2

it's about recurse, think about:

private lock = new ReentrantLock();
public void method() {
      lock.lock();
      method();
}

If the lock is not re-entrant able, the thread could block itself.

Calculus answered 11/4, 2020 at 7:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.