Java object lock: deadlock when calling other methods?

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

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

Calling foo () on (this) will get a lock; will prevent you from trying to do the same when calling foo (and thereby cause a deadlock), or will he realize that the lock is already received by the same thread?

Hope my explanation is more or less clear :-)

+4
source share
3 answers

The synchronized block is reentrant (in fact, Java monitors are reentrant, which is perfectly clear), so there can be no deadlock in your situation.

According to the documents :

Recall that a thread cannot get a lock belonging to another thread. But a thread can get a lock that it already owns.

+10
source

If the stream contains an object lock, it can enter other synchronized blocks based on this lock object.

Here you can read that

"... thread can get a lock that it already owns. Allowing the thread to get the same lock more than once provides re-synchronization. This describes a situation where the synchronized code, directly or indirectly, calls a method that also contains synchronized code, and both sets of code use the same lock.Without re-synchronization, the synchronized code must take many extra precautions to avoid blocking the stream.

+3
source

One thing to be careful though, 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() 
0
source

All Articles