What's a monitor in Java?

JavaMultithreadingConcurrencyMonitor

Java Problem Overview


What's a monitor referred to in concurrent programming in Java?

When I read that "every object has associated a monitor" what does it meaning?

Is it a special object?

Java Solutions


Solution 1 - Java

A monitor is mechanism to control concurrent access to an object.

This allows you to do:

Thread 1:

public void a()
{
    synchronized(someObject) {
        // do something (1)
    }
}

Thread 2:

public void b()
{
    synchronized(someObject) {
        // do something else (2)
    }
}

This prevents Threads 1 and 2 accessing the monitored (synchronized) section at the same time. One will start, and monitor will prevent the other from accessing the region before the first one finishes.

It's not a special object. It's synchronization mechanism placed at class hierarchy root: java.lang.Object.

There are also wait and notify methods that will also use object's monitor to communication among different threads.

Solution 2 - Java

A monitor is an entity that possesses both a lock and a wait set. In Java, any Object can serve as a monitor.

For a detailed explanation of how monitors work in Java, I recommend reading the Monitor Mechanics section of Concurrent Programming in Java (the preceding link displays the preview in Google books, and that section is available for reading).

Solution 3 - Java

  1. A monitor is a concept/mechanism that's not limited to the Java Language;
  2. "In concurrent programming, a monitor is an object or module intended to be used safely by more than one thread";
  3. As every reader knows, every object in Java is a sub-class of java.lang.Object. The java folks made java.lang.Object in such a way that it has features and characteristics that enables Java programmers to use any object as a monitor. For example, every object has a wait queue,a re-entrance queue and wait and notify methods making it a monitor;
  4. read about monitors here.

Solution 4 - Java

In concurrent programming, we need to focus on two things

  1. Mutual exclusion

> When a process/thread is executing its critical section no other processes are allowed to execute their critical section. (Each process has a code segment called "Critical section" in which shared data is accessed.)

  1. Synchronisation

> When threads are trying to achieve a common goal via working together, these threads need cooperation between them. They need to synchronize when they focus on a common goal.

Monitors are used to achieve mutual exclusion and synchronization.


How to understand Monitor easily?

High level view of Monitor

Don't confuse this critical area with the critical section since here, the Critical area mentioned in the object-level, not for the thread level. The shared data is considered as a critical area.

Each object and its class are associated with a monitor. Instance variables of objects that need to be protected from concurrent access included a critical area for a monitor that is associated with the object and Instance variables of classes /static variables of a class that needs to be protected from concurrent access included in the critical area for the monitor which is associated with the class.

  • This critical area is protected with a lock and this lock ensures mutual exclusion.

  • A Wait set is also associated with a monitor that is used to provide coordination between threads.

  • An entry set is used to hold the threads who are already requested for the lock and the lock is not acquired by them yet.

How is mutual exclusion achieved on Monitor?


Each object is associated with a monitor and this monitor has a lock where each thread can lock or unlock the object using this lock when it accesses the shared variables. Explicitly, it means only one thread at a time may hold a lock on a monitor. Any other threads attempting to lock that lock are blocked until they can obtain the lock. when a new thread tries to acquire the lock and if already a thread owns the lock then that thread will be waiting on the entry set to acquire the lock. when the thread which is acquired the lock completes its critical section, it will release the lock. So next thread will acquire the lock but this next thread is taken from the entry set and will be determined by JVM based on some criteria like FIFO.

Here, what we achieved is mutual exclusion since we give exclusive access to a thread to the object and we do not allow any other threads to enter their critical section.

Example java code to achive mutual exclussion using monitor

  class Counter
      {
            private int count = 0;
            public void synchronized Increment() {
                int n = count;
                count = n+1;
            } //Here synchronized is used to indicate those things should be done sequentially.
      }


How is coordination/synchronization achieved via Monitor?

Synchronization is achieved using the wait set which is associated with the monitor and "wait and notify" or "signal and continue" mechanism. Synchronization is important when one thread needs some data to be in a particular state and another thread is responsible for getting the data into that state e.g. producer/consumer problem

When a thread calls the wait() method respect to object then the thread suspended and added to the wait set to wait until some other thread invokes notify() or notifyAll() on the same object.

The notify() method is used for waking up threads that are in the wait set of the monitor of a particular object. There are two ways of notifying waiting threads.

  • notify() --> For all threads waiting on wait set the method notify() notifies anyone of them to wake up arbitrarily. The choice of exactly which thread to wake is non-deterministic and depends upon the JVM.
  • notifyAll() --> This method simply wakes all threads that are waiting on the wait set. The awakened threads will not be able to proceed until the current thread releases the lock on this object. The awakened threads will compete in the usual manner with any other threads that might be actively competing to synchronize.

Example java code to achive synchronization using monitor in producer consumer problem

class Buffer {
            private char [] buffer;
            private int count = 0, in = 0, out = 0;

            Buffer(int size)
            {
                 buffer = new char[size];
            }
 
            public synchronized void Put(char c) {
                 while(count == buffer.length) 
                 {
                      try { wait(); }
                      catch (InterruptedException e) { } 
                      finally { } 
                 } 
                 System.out.println("Producing " + c + " ...");
                 buffer[in] = c; 
                 in = (in + 1) % buffer.length; 
                 count++; 
                 notify(); 
            }
    
            public synchronized char Get() {
                 while (count == 0) 
                 {
                      try { wait(); }
                      catch (InterruptedException e) { } 
                      finally { } 
                 } 
                 char c = buffer[out]; 
                 out = (out + 1) % buffer.length;
                 count--;
                 System.out.println("Consuming " + c + " ..."); 
                 notify(); 
                 return c;
            }
      }

Refer below links http://www.csc.villanova.edu/~mdamian/threads/javamonitors.html#:~:text=Java%20associates%20a%20monitor%20with,the%20monitor%20for%20that%20object https://howtodoinjava.com/java/multi-threading/how-to-use-locks-in-java-java-util-concurrent-locks-lock-tutorial-and-example/

Solution 5 - Java

http://java.sun.com/docs/books/jvms/second_edition/html/Concepts.doc.html#33308

A mechanism to control access to objects one at a time

Solution 6 - Java

The Java language and runtime system support thread synchronization through the use of monitors.
A monitor is associated with a specific data item (a condition variable) and functions as a lock on that data. When a thread holds the monitor for some data item, other threads are locked out and cannot inspect or modify the data.

Solution 7 - Java

Monitor is a synchronization construct that allows threads to have both mutual exclusion and the ability to wait (block) for a certain condition to become true.

Monitors also have a mechanism for signaling other threads that their condition has been met. It is an entity that possesses both a lock and a wait set. In Java, any Object can serve as a monitor.

In the Java virtual machine, every object and class is logically associated with a monitor. To implement the mutual exclusion capability of monitors, a lock (sometimes called a mutex) is associated with each object and class. This is called a semaphore in operating systems terms, mutex is a binary semaphore.

For more information check the link

Solution 8 - Java

http://journals.ecs.soton.ac.uk/java/tutorial/java/threads/monitors.html

monitor is associate with object or data member, which is acquire when a data member or object is enter is synchronization block(critical section) and release when is exit.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionxdevel2000View Question on Stackoverflow
Solution 1 - JavaPablo Santa CruzView Answer on Stackoverflow
Solution 2 - JavaJRLView Answer on Stackoverflow
Solution 3 - JavamgibsonView Answer on Stackoverflow
Solution 4 - JavaRCvaramView Answer on Stackoverflow
Solution 5 - JavanaikusView Answer on Stackoverflow
Solution 6 - Javauser7587921View Answer on Stackoverflow
Solution 7 - JavaSwati GourView Answer on Stackoverflow
Solution 8 - JavaAmit RaiView Answer on Stackoverflow