Junior — Middle
Is it possible to use the synchronized modifier for a static method in Java?
sobes.tech AI
Answer from AI
Yes, in Java, you can use the synchronized modifier for static methods. In this case, the lock occurs at the class level (the Class object), not at the instance level.
This means that if one thread executes a static synchronized method, other threads attempting to call any other static synchronized method of the same class will be blocked until the lock is released.
Example:
public class Example {
public static synchronized void staticMethod() {
// code synchronized on the Example.class object
}
}
Thus, synchronized for static methods provides thread safety at the class level.