Junior — Middle
Explain the principle of operation of a monitor as a mechanism for ensuring thread synchronization.
sobes.tech AI
Answer from AI
A monitor in Java is a synchronization mechanism that ensures mutual exclusion access to shared resources between threads. Each object in Java has an associated monitor.
Working principle:
- When a thread enters a synchronized block or method, it acquires the object's monitor.
- While the monitor is held, other threads attempting to enter the same synchronized block are blocked and wait for the monitor to be released.
- After exiting the block, the monitor is released, and one of the waiting threads gains access.
This guarantees that only one thread executes in the critical section at a time, preventing race conditions and ensuring data correctness.
Example:
synchronized(this) {
// critical section
sharedResource++;
}