Sobes.tech
Junior — Middle

Can two methods declared with the synchronized keyword inside a singleton controller run simultaneously?

sobes.tech AI

Answer from AI

If two methods in the same singleton controller are declared with the synchronized keyword, they are synchronized on the same object — the instance of this singleton. This means that only one of these methods can be executed at a time, and other threads will wait for the monitor to be released.

Thus, two such methods cannot run simultaneously if they are both synchronized and belong to the same object.

Example:

public class SingletonController {
    private static final SingletonController instance = new SingletonController();

    private SingletonController() {}

    public static SingletonController getInstance() {
        return instance;
    }

    public synchronized void methodA() {
        // code
    }

    public synchronized void methodB() {
        // code
    }
}

In this example, if one thread is executing methodA(), another thread that calls methodB() will be blocked until the first one finishes.