Interview Questions

Difference between object lock and class lock?

Java Interview Questions and Answers (part 4)


(Continued from previous question...)

40. Difference between object lock and class lock?

It is very important question from multithreading point of view. We must understand difference between object lock and class lock to answer interview, ocjp answers correctly.

Object lock
Class lock
Thread can acquire object lock by-
Entering synchronized block or
by entering synchronized methods.
Thread can acquire lock on class’s class object by-
1. Entering synchronized block or
2. by entering static synchronized methods.
Multiple threads may exist on same object but only one thread of that object can enter synchronized method at a time.

Threads on different object can enter same method at same time.
Multiple threads may exist on same or different objects of class but only one thread can enter static synchronized method at a time.
Multiple objects of class may exist and every object has it’s own lock.
Multiple objects of class may exist but there is always one class’s class object lock available.
First let’s acquire object lock by entering synchronized block.
Example- Let’s say there is one class MyClass and we have created it’s object and reference to that object is myClass. Now we can create synchronization block, and parameter passed with synchronization tells which object has to be synchronized. In below code, we have synchronized object reference by myClass.
MyClass myClass=new Myclass();
synchronized (myClass) {
}
As soon thread entered Synchronization block, thread acquired object lock on object referenced by myClass (by acquiring object’s monitor.)
Thread will leave lock when it exits synchronized block.
First let’s acquire lock on class’s class object by entering synchronized block.

Example- Let’s say there is one class MyClass. Now we can create synchronization block, and parameter passed with synchronization tells which class has to be
synchronized. In below code, we have synchronized MyClass
synchronized (MyClass.class) {
}


As soon as thread entered Synchronization block, thread acquired MyClass’s class object. Thread will leave lock when it exits synchronized block.
public synchronized void method1() {
}
As soon as thread entered Synchronization method, thread acquired object lock. Thread will leave lock when it exits synchronized method.
public static synchronized void method1() {}

As soon as thread entered static Synchronization method, thread acquired lock on class’s class object.
Thread will leave lock when it exits synchronized method.

(Continued on next question...)

Other Interview Questions