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 there is no keyword to directly create a monitor. To implement a monitor, you must create a new class and use Lock and Condition classes. Lock is the interface is ReentrantLock is the main used implementation, this is the one that we'll learn to use in the current post.
A monitor is a synchronization mechanism that allows threads to have: mutual exclusion – only one thread can execute the method at a certain point in time, using locks. cooperation – the ability to make threads wait for certain conditions to be met, using wait-set.
A lock provides mutual exclusion. This means it prevents multiple threads from accessing the same data at the same time. Notice a monitor uses mutual exclusion. Therefore, locks are used to implement monitors.
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.
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).
In concurrent programming, we need to focus on two things
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.)
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.
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.
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.
}
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.
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/
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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With