It is very important multithreading topic. We must understand this difference to answer interview, ocjp answers correctly.
Difference between object Lock and class Lock >
|
|
|
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.
|
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.
|
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() {
}
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.
|
/** JavaMadeSoEasy.com */
RELATED LINKS>
Differences between important thread methods >
Difference between wait() and sleep() method in threads
Differences and similarities between yield() and sleep() in threads
Difference between notify() and notifyAll() methods, with program
Difference between wait() and wait(long timeout) -What will be Thread states
Object and class lock >
Acquiring object lock - synchronization blocks and methods- multiple threads may exist on same object but only one thread of that object can enter synchronized block/method at a time.
Acquiring lock on class, 2 Ways to acquire lock on class
Difference between object Lock and class Lock
Guidelines to threadsafe code >
Guidelines to thread safe code, most important point we must take care of in multithreading programs
Interviews >