Immagine that I have Class First
with several synchronised methods. When a thread locks the class First
, does it lock per method or per class? For example does deadlock happen for the following code?
public class DeadLockQuestion {
public static class First{
public synchronized void a(){
}
public synchronized void b(){
}
public synchronized void c(){
}
public synchronized void d(){
}
public synchronized void e(){
}
}
public static void main(String... args){
First f = new First();
//This code is run in Thread 1
f.a();
// End
//This code is run in Thread 2 simultanously
f.b();
//End
// We have also Threads 3 & 4 & 5 that invoke c,d and e simultanously
}
}
You have got two locks in Java. One is
Object
lock. and the other isClass
Lock. Theobject lock
locks access to synchronized non-static functions only. andClass lock
locks on synchronized static functions only. For you, its anobject lock
on objectf
. So all the synchronized non-static functions are locked for objectf
. Since all the Threads are using the same objectf
, Only one Thread will be able to access your non-static functionsa(), b(),...
at a time. Read more hereNo, it won't happen in your case. Because While one
Thread
is holding the lock, Other threads can't get inside your synchronized function.DeadLock happens due to resources.
You have only one resource thats Object
f
. There's no point of a dead-lock here because the class First doesn't lock another object and no cyclic lock can happen. Deadlock requires a cyclic lock!Some Info:
Useful Source Here, and here
Firstly, Deadlock occurs with threads and not classes or methods.
Deadlock occurs when there is a cyclic dependency of locks.
Image source: FusionReactor deadlock plugin
To lock each method independently use a synchronized block within each method and lock on a different object.
If you have an appropriate (and it should be final to prevent potential problems) object already within the class you can use that. If not create a
private final Object aLock = new Object();
and then lock on that, for example:Always hold the lock for as long as you need it, but no longer.
Deadlock happens to threads, not to methods or classes.
The deadlocked threads also hold locks, but in this case it is impossible to tell which locks because you do not demonstrate an actual deadlock scenario (if two threads call synchronized methods of
f
one goes through and the other waits; deadlock requires at least two locks).When
a()
is a synchronized method,f.a()
literally means:So in this case a lock would happen for object monitor
f
. In your case you would require a second object to create a deadlock, I don't think it's possible to create a deadlock with a single object monitor. A typical deadlock pattern is when an order of lock acquisition is not being maintained, i.e. when this happens in two different threads: