Junior — Middle
Can two static methods declared with the synchronized modifier be executed simultaneously within a singleton controller?
sobes.tech AI
Answer from AI
In Java, if two static methods are declared with the synchronized modifier, they synchronize on the class object (Class object), not on an instance.
Since a singleton is a single instance of a class, but static methods are not tied to an instance, they are tied to the class, so both methods lock the same class monitor.
This means that two such static synchronized methods cannot be executed simultaneously within the same class (including a singleton), because they use the same monitor.
Example:
public class SingletonController {
public static synchronized void methodA() {
// locks the monitor of the SingletonController class
}
public static synchronized void methodB() {
// locks the same monitor of the class
}
}
Calling methodA and methodB from different threads will be sequential, not parallel.