Java object locking: Deadlock when calling other methods?

deadlock, java, locking, multithreading

Solution

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.

Problem

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

Original source