Sobes.tech
Junior — Middle

When using the keyword synchronized, on which object is the locking mechanism performed?

sobes.tech AI

Answer from AI

In Java, when using the synchronized keyword, the locking mechanism depends on the context:

  • If synchronized is applied to a non-static method, the lock occurs on the object (this) on which the method is called.
  • If synchronized is applied to a static method, the lock occurs on the class object (Class), that is, on the class itself.
  • If a synchronized(obj) block is used, the lock occurs on the obj object.

Example:

public class Example {
    public synchronized void instanceMethod() {
        // lock on this
    }

    public static synchronized void staticMethod() {
        // lock on Example.class
    }

    public void blockMethod() {
        Object lock = new Object();
        synchronized(lock) {
            // lock on lock
        }
    }
}
When using the keyword synchronized, on which object… - sobes.tech