Reputation: 207
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?
Upvotes: 3
Views: 2012
Reputation: 279960
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.
Upvotes: 15
Reputation: 2279
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.
Upvotes: 1