How does the 'synchronized' synchronization mechanism work under the hood in Java?
sobes.tech AI
Answer from AI
The synchronized mechanism in Java is based on the concept of monitors (monitor objects). Each object in Java is associated with a monitor.
When a thread enters a synchronized block or method, it attempts to acquire the monitor of the corresponding object. If the monitor is free, the thread acquires it and continues execution. If the monitor is occupied by another thread, the current thread is blocked and enters a waiting state until the monitor is released.
When a thread leaves a synchronized block or method (either by completing it successfully or by throwing an exception), it releases the monitor.
Inside the monitor, the following are implemented:
- Mutual Exclusion: Only one thread can own the monitor of an object at a time. This guarantees that only one thread can execute synchronized code for that object.
- Waiting and Notification: The monitor includes a set of related methods
wait(),notify(), andnotifyAll(). These methods allow threads owning the monitor to temporarily release it and enter a waiting state, then be notified by other threads when they can continue work.
The underlying implementation involves:
monitorenterinstruction: Executed when entering a synchronized block or method. Attempts to acquire the object's monitor.monitorexitinstruction: Executed when leaving a synchronized block or method (whether normally or due to an exception). Releases the object's monitor.
These instructions are part of Java bytecode and are processed by the Java Virtual Machine (JVM). The JVM uses native operating system mechanisms (such as mutexes, semaphores) to manage monitors and thread locking/unlocking.
Monitor acquisition can be implemented at the object level (for instance methods and blocks) or at the class level (for static methods and blocks), using the Class object as a lock.
Example usage:
public class Counter {
private int count = 0;
public synchronized void increment() { // Synchronized method
count++;
}
public void decrement() {
synchronized (this) { // Synchronized block
count--;
}
}
public static synchronized void staticMethod() { // Synchronized static method
// ...
}
}
Table of Object class methods related to monitors:
| Method | Description |
|---|---|
wait() |
The thread owning the monitor temporarily releases it and enters a waiting state. |
notify() |
Notifies one of the waiting threads that it can attempt to acquire the monitor and resume work. |
notifyAll() |
Notifies all waiting threads. |