Reputation: 21
in below code snippet, i have one question. threads will acquire class level lock or Object level Lock ?
private static Object lock=new Object();
private static Object lock2=new Object();
public static void m1(){
synchronized(lock){
//statements
}
}
public static void m2(){
synchronized(lock2){
//statements
}
}
Upvotes: 1
Views: 163
Reputation: 1478
You have explicitly used Object class instance as monitor object in you synchronized
code block, which means it will take lock on those objects only.
A code block use Class itself as monitor object when you define a function as static
and synchronized
both. Because when you define a static function, that function belongs to class itself, means you don't need a class instance to invoke such functions. So if a static function is defined as synchronized
then its execution in multithreaded environment will need to take a lock on some common monitor object among all such threads, which in such cases is class
itself.
Note - Every class definition itself is an instance of java.lang.Class
Upvotes: 1
Reputation: 46305
Every object has a "monitor". When you use a synchronized block you specify the instance whose monitor you want to synchronize on. In addition to synchronized blocks there are also synchronized methods. A synchronized instance method will acquire the monitor of the instance the method was invoked on, whereas a synchronized static method will acquire the monitor of the java.lang.Class
object of the enclosing class.
public class Foo {
private static final Object STATIC_LOCK = new Object();
private final Object instanceLock = new Object();
public static void bar() {
synchronized (STATIC_LOCK) { // acquires monitor of "STATIC_LOCK" instance
// guarded code
}
}
public static synchronized void baz() { // acquires monitor of "Foo.class" instance
// guarded code
}
public void qux() {
synchronized (instanceLock) { // acquires monitor of "instanceLock" instance
// guarded code
}
}
public synchronized void quux() { // acquires monitor of "this" instance
// guarded code
}
}
Upvotes: 1