public class Foo {
public static synchronized classMethod() { } (1)
public synchronized void instanceMethod() { } (2)
}
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.
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:
- BlackRock Java Interview Questions
- Multi-threading Java Interview Questions for Investment Bank
- Morgan Stanley Java Interview Questions
- Cracking core java interviews - question bank
- Sapient Global Market Java Interview Questions and Coding Exercise
- Java Concurrency Interview Questions
- Citibank Java developer interview questions