title: Difference between class locking and object locking in Java
body: <p>People tell about two types of multi-threaded locking - object and class. In my knowledge, locking is done on objects only.</p>
  
  <p><strong>Case 1: On objects we create</strong> using <code>new</code> or factory methods etc.</p>
  
  <pre><code>void synchronized myMethod(Type param) {
    //will lock on the instance used to call this method
  }
  </code></pre>
  
  <p>or</p>
  
  <pre><code>synchronized(this) {
   //will lock on current object
  }
  </code></pre>
  
  <p>or</p>
  
  <pre><code>synchronized(obj1) {
   //will lock on specified obj1 object
  }
  </code></pre>
  
  <p><strong>Case 2: On <code>java.lang.Class</code> objects</strong></p>
  
  <p>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.</p>
  
  <pre><code>static void synchronized method() {
    //will lock the Class object
  }
  </code></pre>
  
  <p>or</p>
  
  <pre><code>static {
    synchronized(SomeClass.class){
      int a = 2;
    }
  }
  </code></pre>
  
  <ul>
  <li>Why I am thinking this also as an object locking because classes are loaded into the Method Area in the JVM, and <strong>all the static properties of the class are wrapped inside a <code>java.lang.Class</code> object created by JVM</strong>. So behind abstraction, its object locking and in the picture, we see Class locking.</li>
  <li>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 <code>java.lang.Class</code> instance) also works in same manner.</li>
  <li><p>I want to know in case of synchronized static methods, lock on which class is acquired by the thread in following two cases:</p>
  
  <ol>
  <li>This method is called from same class where it is defined.</li>
  <li>This method is called from derived class with derived class name.</li>
  </ol></li>
  </ul>
  
  <p>This is my understanding so far regarding the subject. Please add on or rectify.</p>