Java – synchronization block within synchronization block
Can I include a synchronization block in another object to synchronize another object?
Example:
synchronized(myObjetc1){ // code synchronized(myObjetc2){ // code } }
If so, is it still the right technology or is it too risky?
Solution
If you synchronize in the same order elsewhere, it's no problem
If some other threads want to execute the following code
synchronized(myObjetc2){ // code synchronized(myObjetc1){ // code } }
You may encounter an impasse
Assuming that the above variables refer to the same object, consider the following The first thread (your code) locks the monitor on myobjetc1 Thread scheduler switches thread context The second thread (code above) locks the monitor on myobjetc2 Thread scheduler switches thread context The first thread attempts to lock the monitor on myobjetc2 It must wait because the second thread has it Thread scheduler switches context The second thread attempts to lock the monitor on myobjetc1 It must wait because the first thread has it boom! Deadlock