I have this class:
public class MyClass {
public MyClass(){}
public void actionA(){
synchronized(MyClass.class){
System.out.print("A");
}
}
public void actionB(){
synchronized(MyClass.class){
actionA();
}
}
}
Which one (if any) is true?
- Calling actionB() will lead to a deadlock, since actionA() can never aquire the lock associated with MyClass.class
- Calling actionB() will not lead to a deadlock, since it already has aquired the lock associated with MyClass.class
#2will happen, since the calling thread has the lock.If however the code looked like this:
Then you would have a deadlock.
locksare acquired on a per thread basis.I find a useful mental picture is of a shared key for a padlock. Only one thread can have the key at a time, but obviously the same key will open any lock which it fits (the key fits any lock that uses the same sync object).
As an aside, it is bad practice to synchronize on any publicly visible field, since another piece of code far removed could feasibly lock on the same object leading to unnecessary contention and possibly deadlocks.