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
synchronizedis applied to a non-static method, the lock occurs on the object (this) on which the method is called. - If
synchronizedis 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 theobjobject.
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
}
}
}