Hossain Margani Hossain Margani -4 years ago 152
Java Question

Nested synchronized keyword

I have this code in Java:

public void doSomeThing() {
synchronized (this) {
public void doSomeThingElse() {
synchronized (this) {
// do something else

Can this code block? I mean, Can this code wait for ever?

Answer Source

As the java documentation describes for Reentrant locking:

a thread can acquire a lock that it already owns

The second synchronized block is using the same lock and thus will always be useable as the lock has already been aquired in the outer method.

No, there will not be a deadlock.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download