![]() |
VOOZH | about |
Lock and Monitor in Java are both used to manage synchronization and control access to shared resources in multithreading. They help ensure thread safety but differ in flexibility and usage.
A monitor in Java is a mechanism used to control access to shared resources in multithreading. It ensures that only one thread can access a synchronized block or method at a time.
synchronized, wait(), notify(), and notifyAll() for thread communication.Geeks for Geeks
Explanation: Only one thread prints at a time because the synchronized method locks the monitor.
Lock is a tool for controlling access to shared resources by multiple threads. Itβs part of the java.util.concurrent.locks package, introduced in Java 5 and is an alternative to the traditional synchronized keyword.
Below is the illustration which demonstrates the functioning of basic locks.
Final value of sharedResource: 2000
Explanation:
| Aspect | Monitor (synchronized) | Lock (ReentrantLock) |
|---|---|---|
| Origin | JVM intrinsic, low-level primitive | Java 5, high-level API |
| Implementation | Implicit, JVM-managed | Explicit, programmer-managed |
| Critical Section Management | Automatic | Manual (lock() / unlock()) |
| Thread Queueing | JVM manages waiting threads | Programmer can choose fairness policies |
| Features | Simple mutual exclusion | Advanced: fairness, interruptible, tryLock, multiple conditions |
| Performance | Lightweight for small threads | Slightly higher overhead, but more flexible |
| Usage | Simple synchronization, small thread pools | Complex synchronization, high concurrency scenarios |
| Deadlock Handling | Less control | More explicit control but can still occur |
Note: As monitors themselves are implemented with the necessary support of locks, it is often said that they are not different but complementary in their existence.