Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java object locking: Deadlock when calling other methods?

If I use synchronize(this) in two methods and one calls the other, will I get stuck in a deadlock situation or will it work because the thread already owns the lock?

Picture the class below:

public class Test {
  public void foo() {
    synchronize(this) {
      bar();
    }
  }

  public void bar() {
    synchronize(this) {
      // do something
    }
  }
}

As you can see, there are two methods foo and bar, which both rely on synchronization.

When calling foo(), a lock will be obtained on (this); will bar try to do the same when called by foo (and thus causing a deadlock) or will it realize that the lock has already been obtained by the same thread?

Hope my explanation is more or less clear ;-)

like image 872
usimon Avatar asked Dec 13 '22 01:12

usimon


2 Answers

The synchronized block is reentrant (in fact, Java monitors are reentrant, to be perfectly clear), thus no deadlock can happen in your situation.

According to the docs:

Recall that a thread cannot acquire a lock owned by another thread. But a thread can acquire a lock that it already owns.

like image 96
Tudor Avatar answered Jan 12 '23 04:01

Tudor


If thread holds lock of object it can enter to other synchronized blocks based on that lock object.

Here you can read that

"...thread can acquire a lock that it already owns. Allowing a thread to acquire the same lock more than once enables reentrant synchronization. This describes a situation where synchronized code, directly or indirectly, invokes a method that also contains synchronized code, and both sets of code use the same lock. Without reentrant synchronization, synchronized code would have to take many additional precautions to avoid having a thread cause itself to block."

like image 28
Pshemo Avatar answered Jan 12 '23 04:01

Pshemo