简体   繁体   中英

Synchronized block inside synchronized block

May I include a synchronized block inside another one for synchronizing another object?

Example:

synchronized(myObjetc1){
    // code
    synchronized(myObjetc2){
        // code         
    }           
}

If so, still, is it a correct technique or is it too risky?

It will be fine if you synchronize in the same order everywhere else.

If some other thread were to execute the following code

synchronized(myObjetc2){
    // code
    synchronized(myObjetc1){
        // code         
    }           
}

you might get a deadlock.

Assuming the variables above are referencing the same objects, consider the following case. The first thread (your code) locks the monitor on myObjetc1 . The thread scheduler switches thread context. The second thread (the above code) locks the monitor on myObjetc2 . The thread scheduler switches thread context. The first thread attempts to lock the monitor on myObjetc2 . It has to wait because the second thread has it. The thread scheduler switches context. The second thread attempts to lock the monitor on myObjetc1 . It has to wait because the first thread has it. Boom! Deadlock.

Yes, you can do it.

Till the time you are following lock rules and doing so solves your requirement, its Fine.

However, many times something like this invites DeadLock problem, if done incorrectly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM