Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested synchronized keyword

I have this code in Java:

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

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

like image 317
Hossein Margani Avatar asked Feb 03 '11 08:02

Hossein Margani


People also ask

Can synchronized block be nested?

public void doSomething() { synchronized(lock1) { synchronized(lock2) { // ... } } } public void doOtherthing() { synchronized(lock2) { synchronized(lock1) { // ... } } } now if more than one thread are trying to access these methods then there may be a deadlock because of nested synchronized blocks.

What is the synchronized keyword?

The synchronized keyword prevents concurrent access to a block of code or object by multiple threads. All the methods of Hashtable are synchronized , so only one thread can execute any of them at a time.

What is nested monitor lockout?

Nested monitor lockout is a problem similar to deadlock. A nested monitor lockout occurs like this: Thread 1 synchronizes on A Thread 1 synchronizes on B (while synchronized on A) Thread 1 decides to wait for a signal from another thread before continuing Thread 1 calls B.

Which is more efficient synchronized method or synchronized block?

From this we can conclude that synchronizing on the smallest possible code block required is the most efficient way to do it. However the practical difference between synchronizing a method vs. a code block really depends on the method and what code is being left out of the synchronized block.


2 Answers

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.

like image 52
Kissaki Avatar answered Oct 04 '22 07:10

Kissaki


If a thread owns the lock on this, it will go into other synchronized methods/block like hot knife in butter.

like image 44
fastcodejava Avatar answered Oct 04 '22 06:10

fastcodejava