Sobes.tech
Junior — Middle

At what level is the monitor that provides synchronization inside a non-static method using the synchronized keyword?

sobes.tech AI

Answer from AI

In Java, when a non-static method is declared with the synchronized keyword, the monitor (lock) is taken on the instance of the object for which the method is called. That is, synchronization occurs at the level of a specific object of the class, not at the class level as a whole.

Example:

public class MyClass {
    public synchronized void myMethod() {
        // code synchronized on this
    }
}

In this example, the monitor is the this object — the current instance of the MyClass class. If multiple threads call this method on the same object, they will be synchronized, but calls on different objects can execute in parallel.

At what level is the monitor that provides… - sobes.tech