How does the keyword synchronized interact with the monitor when used on a method?
sobes.tech AI
Answer from AI
In Java, the keyword synchronized, when applied to a method, means that when this method is called, the thread must acquire the monitor (lock) of the object to which the method belongs:
- For non-static methods, the monitor is the object itself (
this). - For static methods, the monitor is the class object (
Class).
When a thread calls a synchronized method, it attempts to acquire the monitor. If the monitor is already held by another thread, the calling thread blocks until the monitor is released.
Thus, synchronized on a method provides mutual exclusion (mutex) for all calls to that method on a single object (or class for static methods), preventing multiple threads from executing the method's code simultaneously.
Example:
public synchronized void increment() {
count++;
}
Here, increment can only be executed by one thread at a time on an object, as the thread must acquire the object's monitor before executing.