public void method(Type1 inst1, Type2 inst2) {
synchronized(inst1) {
synchronized(inst2) {
//do something now
}
}
}
I can understand from this piece of code that once a thread enters the method, it acquires the lock on inst1, and then it acquires lock on inst2, without releasing inst1 lock. I assume that both of these objects are not locked by other thread.
1 . If a thread can acquire lock on only one object at once and can only own another lock when lock on current object has been released, how can this piece of code be valid, or rather, is it a valid code that I think I have seen somewhere?
It is a valid code, the locks are not on the object where the method resides, but on inst1 and inst2. Also, the lock is not on the class, but for every object
2 . And what if Type1 and Type2 are same?
again, the locks are on the objects, not on the classes. if inst1 and inst2 are the same, then the thread has only one lock, it is valid for the same thread to "re-enter" the lock
3 . What happens if we make the method synchronized, considering it resides in a class other than the parameter types of the method?
Then you have yet another lock, this time on the object (not the class) where the method is being executed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With