![]() |
VOOZH | about |
A monitor in Java is a synchronization mechanism that controls concurrent access to an object. It ensures that only one thread can execute critical section (a block of code that accesses shared resources) at a time, while other threads wait. When a thread enters a synchronized block:
Mutual Exclusion ensures that only one thread can execute a synchronized section of code at a time. Example: Only one thread can update a shared variable at a time.
Thread Coordination allows threads to communicate and coordinate with each other using:
Example: Implementing a Monitor Using the synchronized Keyword
Output:
Note: The output order may vary depending on thread scheduling, but due to synchronization, one thread completes its entire loop before the other begins.
| Feature | Monitor | Lock |
|---|---|---|
| How it works | Built-in synchronization mechanism using the synchronized keyword. | A manual locking mechanism from java.util.concurrent.locks package. |
| Control | Automatically handled by JVM, no need to explicitly lock or unlock. | Developer manually controls access using lock() and unlock(). |
| Flexibility | Simple but limited, cannot try or interrupt while waiting. | Very flexible , supports tryLock(), lockInterruptibly(), and fairness options. |
| Thread Communication | Uses wait(), notify(), and notifyAll() methods. | Uses Condition objects for better thread coordination. |
| Performance | Easier to use but slower under heavy thread contention. | More efficient and scalable for high-concurrency applications. |