Saturday, March 26, 2016

Class level Lock vs Instance Lock

Each java class and its instance  have its associated intrinsic lock.

For a particular class, a  JVM will load its .class only one with a particular class loader. The static members of a class belong to a .class instance. Hence acquiring  class level lock, we can have synchronization mechanism for static members of a class. Having lock on class level , will lock
access to non static methods too by another thread.

Lets consider a class Test1, it has few static methods and few non static methods.

class Test1 {

public  static synchronized void doStuffStatic1(){
System.out.println("invoking static method 1 ####");

}

public  static synchronized void doStuffStatic2(){
System.out.println("invoking static method2####");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

public synchronized void doStuff1(){
System.out.println("invoking instance method 1####");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

public synchronized void doStuff2(){
System.out.println("invoking instance method 2####");

}

}

If a thread acquires a class level lock, another thread can not access any of its static or non-static
 methods.

public static void main(String[] args) {

Test1 test = new Test1();

Thread t1 = new Thread(new Runnable() {

@Override
public void run() {

synchronized (Test1.class) {
test.doStuff1();

}
}
});

Thread t2 = new Thread(new Runnable() {

@Override
public void run() {


Test1.doStuffStatic1();
test.doStuff2();


}
});

t1.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
t2.start();


}


No comments:

Post a Comment