Java: nested synchronization blocks

I saw this in a Heinz Kabutz Java Specialist news release and, although all the articles (and indeed all) of Dr. Kabutz’s articles are well explained and detailed, he seemed to be silent about what this code does, or more importantly:

public class SomeObject { private Object lock1; private Object lock2; public void doSomething() { synchronized(lock1) { synchronized(lock2) { // ... } } } } 

What are the consequences of nested synchronized blocks? How does this affect the various threads trying to do doSomething() ?

+14
java multithreading concurrency
Apr 28 '12 at 15:53
source share
3 answers

There are two possible problems that need to be addressed.

  • Nested locks can lead to deadlocks quite easily if you use wait / notify. Here is an explanation of the reasons. http://tutorials.jenkov.com/java-concurrency/nested-monitor-lockout.html

  • It should be feared that if another method wants to lock the same two objects, they should always do it in the same order, otherwise there is the possibility of a different deadlock situation described in this message: How to avoid nested synchronization and as a result of a deadlock

+25
Apr 28 '12 at 16:10
source share

This piece of code alone will not cause any problems. But the problem can occur as a dead end if there is something like this code; where we have two methods with synchronized blocks in such a way that objects are locked in opposite orders -

 public void doSomething() { synchronized(lock1) { synchronized(lock2) { // ... } } } public void doOtherthing() { synchronized(lock2) { synchronized(lock1) { // ... } } } 

now, if more than one thread is trying to access these methods, then there might be a dead end due to nested synchronized blocks.

+1
Aug 7 '15 at 17:55
source share

According to Nested Monitor Lock Tutorial

In the nested monitor lock in Thread 1, A locks and waits for the signal from thread 2. Thread 2 requires A lock to send the signal to thread 1. At the dead end, two threads are waiting from each other to release the locks.

The impasse may be similar to two persons imprisoned in two rooms, they want to switch to another room, but both of them have only a copy of them. While the nested monitor lock is exactly the same as the boss is designed to sleep in the room, and suppose he wakes up only when someone enters the room. And the secretary is responsible for awakening his boss. But the boss still held the key to the room when he was sleeping, so the secretary could not come to wake him.

0
Dec 30 '16 at 9:39
source share



All Articles