usimon
usimon

Reputation: 445

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 ;-)

Upvotes: 4

Views: 572

Answers (3)

John Kane
John Kane

Reputation: 4443

One thing to be careful of though is if:

Thread A has the lock in foo() and needs to call bar()

and Thread B has the lock in bar() while needing to call foo()

Upvotes: 0

Pshemo
Pshemo

Reputation: 124245

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."

Upvotes: 3

Tudor
Tudor

Reputation: 62439

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.

Upvotes: 10

Related Questions