public class Foo {
public static synchronized classMethod() { } (1)
public synchronized void instanceMethod() { } (2)
}
Static method synchronization aka Class Lock in Java
Carvia Tech | August 05, 2019 | 1 min read | 388 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.
1 | static synchronization (Class Lock) |
2 | instance synchronization (Instance Lock) |
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
-
One Thread can call
classMethod()
and other thread can callinstanceMethod()
in parallel because class level and instance level locks do not interfere. -
But both the threads can’t call the same
instanceMethod()
or the sameclassMethod()
in parallel, because of the Mutual Exclusiveness of the Instance Lock and Class Lock.
Top articles in this category:
- Top 50 Multi-threading Java Interview Questions for Investment Bank
- Citibank Java developer interview questions
- Java Concurrency Interview Questions and Answers
- Sapient Global Market Java Interview Questions and Coding Exercise
- Morgan Stanley Investment Banking Java Interview Questions
- BlackRock Top Java Interview Questions: Investment Banking Domain
- Cracking core java interviews - question bank
Find more on this topic:

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:
Similar Posts
- Send GMAIL emails from Java and Spring
- Send Mandrill emails from Spring Boot in Java
- Top 30 Hibernate and Spring Data JPA interview questions
- Generating variable length secure key/secret in Java
- Reverse the bits of a number and check if the number is palindrome or not
- MD5 and SHA-256 in Java Kotlin and Android
- Spring Security 5 - There is no PasswordEncoder mapped for the id
- Inter-thread communication in Java
- What are different thread states in Java
- Static method synchronization aka Class Lock in Java
Enter your email address to subscribe to this blog and receive notifications of new posts by email.