Interview Questions

Can we acquire lock on class? What are ways in which you can acquire lock on class?

Java Interview Questions and Answers (part 4)


(Continued from previous question...)

39. Can we acquire lock on class? What are ways in which you can acquire lock on class?

Yes, we can acquire lock on class’s class object in 2 ways to acquire lock on class.

Thread can acquire lock on class’s class object by-

1. Entering synchronized block or
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) {
//thread has acquired lock on MyClass’s class object.
}


2. by entering static synchronized methods.
public static synchronized void method1() {
//thread has acquired lock on MyRunnable’s class object. }


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

(Continued on next question...)

Other Interview Questions