Static method synchronization aka Class Lock in Java

Carvia Tech | August 05, 2019 | 1 min read | 2 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. Top 50 Multi-threading Java Interview Questions for Investment Bank
  2. Citibank Java developer interview questions
  3. Sapient Global Market Java Interview Questions and Coding Exercise
  4. Morgan Stanley Investment Banking Java Interview Questions
  5. BlackRock Top Java Interview Questions: Investment Banking Domain
  6. RBS Java Programming Interview Questions
  7. Cracking core java interviews - question bank



Find more on this topic:
Java Interviews image
Java Interviews

Interview - Product Companies, eCommerce Companies, Investment Banking, Healthcare Industry, Service Companies and Startups.

Last updated 1 week ago


Recommended books for interview preparation:

This website uses cookies to ensure you get the best experience on our website. more info