Static method synchronization aka Class Lock in Java

Upasana | August 05, 2019 | 1 min read | 733 views


There is one copy of static data per class, so we only need one lock per class to synchronize static methods. Every class loaded by JVM has a corresponding instance of java.lang.Class representing that class. This java.lang.Class instance’s lock is used t protect any synchronized static methods of the class. Synchronization on static method does not interfere with instance level synchronization as the first one is one lock per class (on java.lang.Class) and second one is one lock per instance, hence there is no linking between the two.

Static synchronization example

Static synchronization can be achieved either at the method level or at the block level, as shown in below code snippets.

Class and Instance lock at method level
public class Foo {
    public static synchronized classMethod() {  }   (1)

    public synchronized void instanceMethod() {  }  (2)
}
1 static synchronization (Class Lock)
2 instance synchronization (Instance Lock)
Class and Instance lock at code block level
public class Foo {
    public static classMethod() {
        synchronized(Foo.class){    (1)

        }
    }

    public void instanceMethod() {
        synchronized(this){     (2)

        }
    }
}
1 Class lock using block of code
2 Instance lock using block of code

Important points

  1. One Thread can call classMethod() and other thread can call instanceMethod() in parallel because class level and instance level locks do not interfere.

  2. But both the threads can’t call the same instanceMethod() or the same classMethod() in parallel, because of the Mutual Exclusiveness of the Instance Lock and Class Lock.


Top articles in this category:
  1. BlackRock Java Interview Questions
  2. Multi-threading Java Interview Questions for Investment Bank
  3. Morgan Stanley Java Interview Questions
  4. Cracking core java interviews - question bank
  5. Sapient Global Market Java Interview Questions and Coding Exercise
  6. Java Concurrency Interview Questions
  7. Citibank Java developer interview questions

Recommended books for interview preparation:

Find more on this topic: