Search code examples
javamultithreadinglockingthread-synchronization

Difference between class locking and object locking in Java


People tell about two types of multi-threaded locking - object and class. In my knowledge, locking is done on objects only.

Case 1: On objects we create using new or factory methods etc.

void synchronized myMethod(Type param) {
  //will lock on the instance used to call this method
}

or

synchronized(this) {
 //will lock on current object
}

or

synchronized(obj1) {
 //will lock on specified obj1 object
}

Case 2: On java.lang.Class objects

This is called class lock, and can be used with static fields or methods or blocks, as they belong to class and shared among all the objects, and other class properties.

static void synchronized method() {
  //will lock the Class object
}

or

static {
  synchronized(SomeClass.class){
    int a = 2;
  }
}
  • Why I am thinking this also as an object locking because classes are loaded into the Method Area in the JVM, and all the static properties of the class are wrapped inside a java.lang.Class object created by JVM. So behind abstraction, its object locking and in the picture, we see Class locking.
  • So I can also infer one more thing. Just as objects locked by a thread can not be acquired by another thread as long as it is not released by first thread, class locking (the java.lang.Class instance) also works in same manner.
  • I want to know in case of synchronized static methods, lock on which class is acquired by the thread in following two cases:

    1. This method is called from same class where it is defined.
    2. This method is called from derived class with derived class name.

This is my understanding so far regarding the subject. Please add on or rectify.


Solution

  • The only difference is that a static synchronized locks on the class instance and a non-static synchronized method locks on the instance.

    People tell about two types of multi-threaded locking

    There is object instance locks and Lock style locks. A Lock, confusingly, has both.

    object and class

    Not true as you have worked out already.

    Just because people say stuff doesn't make it true. Often people say a lot of nonsense. In fact there is whole web sites devoted to non-sense about Java. :P