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.