Difference Between Object Lock and Class Lock
Difference Between Object Lock and Class Lock
Difference Between Object Lock and Class Lock
Thread can acquire object lock by- Thread can acquire lock on class’s class object
1. Entering synchronized block or by-
2. by entering synchronized methods. 1. Entering synchronized block or
2. by entering static synchronized methods.
Multiple threads may exist on same object but only one thread of that Multiple threads may exist on same or different objects of
object can enter synchronized method at a time. class but only one thread can enter static synchronized
method at a time.
Threads on different object can enter same method at same time.
Multiple objects of class may exist and every object has it’s own Multiple objects of class may exist but there is always
lock. one class’s class object lock available.
First let’s acquire object lock by entering 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 and we have created it’s
object and reference to that object is myClass. Now we can create Example- Let’s say there is one class MyClass. Now we
synchronization block, and parameter passed with synchronization tells can create synchronization block, and parameter passed
which object has to be synchronized. In below code, we have with synchronization tells which class has to be
synchronized object reference by myClass. synchronized. In below code, we have synchronized
MyClass myClass=new Myclass();
MyClass
synchronized (myClass) {
} synchronized (MyClass.class) {
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. As soon as thread entered Synchronization block, thread
acquired MyClass’s class object. Thread will leave lock
when it exits synchronized block.
/** JavaMadeSoEasy.com */
RELATED LINKS>