VOOZH about

URL: https://www.geeksforgeeks.org/java/monitor-in-java/

⇱ Monitor in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Monitor in Java

Last Updated : 30 Oct, 2025

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:

  • It requests the monitor of the object.
  • If the monitor is available, it acquires it and executes the synchronized code.
  • If another thread already holds the monitor, the new thread waits until the monitor is released.
  • After execution, the thread releases the monitor, allowing other threads to acquire it

Key Concepts of Monitors

1. Mutual Exclusion

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.

2. Thread Coordination

Thread Coordination allows threads to communicate and coordinate with each other using:

  • wait() -> Thread releases the monitor and waits.
  • notify() -> Wakes up one waiting thread.
  • notifyAll() -> Wakes up all waiting threads.

Example: Implementing a Monitor Using the synchronized Keyword

Output:

👁 output
output

Explanation

  • The synchronized (this) block acquires the monitor lock of the current object.
  • When one thread executes the printTable() method, the other thread must wait until the first one releases the monitor.
  • This ensures mutual exclusion, preventing data inconsistency and race conditions.

Note: The output order may vary depending on thread scheduling, but due to synchronization, one thread completes its entire loop before the other begins.

Monitor vs Lock

Feature Monitor Lock
How it worksBuilt-in synchronization mechanism using the synchronized keyword.A manual locking mechanism from java.util.concurrent.locks package.
ControlAutomatically handled by JVM, no need to explicitly lock or unlock.Developer manually controls access using lock() and unlock().
FlexibilitySimple but limited, cannot try or interrupt while waiting.Very flexible , supports tryLock(), lockInterruptibly(), and fairness options.
Thread CommunicationUses wait(), notify(), and notifyAll() methods.Uses Condition objects for better thread coordination.
PerformanceEasier to use but slower under heavy thread contention.More efficient and scalable for high-concurrency applications.


Comment
Article Tags: