mercredi 25 février 2015

Can more than 1 threads execute a static synchronized method in JAVA



I've been looking all over the web trying to find information on how static synchronized methods are allowed to be executed. What I found is that a static synchronized method will acquire the class lock. As far as I understand it, this ensures that only one of all the existent class instances will be allowed to execute the static synchronized method. Is this really the case? Can there be 2 class instances executing the static synchronized method concurrently, or not? So, to make it more visual, I'm adding a code-sample.



public class A {

private static synchronized void m1() {
//Print something
}

private synchronized void m2() {
//Print something else
}
}


I understand that, because the static method is acquiring the class level monitor and the non-static method is acquiring the object-level monitor, then both can execute at the same time from 2 different threads like so:



A a = new A;
a.m2();//object-level lock acquired
a.m1();//Class-level lock acquired


However if we have 3 instances of the above class, can they all concurrently run m1()? I think they can't, but I am not sure. So can this happen?



A a = new A;
A aa = new A;
A aaa = new A;

a.m1();
aa.m1();
aaa.m1();



Aucun commentaire:

Enregistrer un commentaire