| next>><<prevReentrant Monitor in JavaLast Updated : 17 Mar 2025According to Sun Microsystems,Java monitors are reentrantmeans java thread can reuse the same monitor for different synchronized methods if method is called from the method.Advantage of Reentrant MonitorIt eliminates the possibility of single thread deadlockingLet's understand the java reentrant monitor by the example given below:class Reentrant {
public synchronized void m {
n;
System.out.println("this is m method");
}
public synchronized void n {
System.out.println("this is n method");
}
}In this class, m and n are the synchronized methods. The m method internally calls the n method.Now let's call the m method on a thread. In the class given below, we are creating thread using annonymous class.public class ReentrantExample{
public static void main(String args){
final ReentrantExample re=new ReentrantExample;
Thread t1=new Thread{
public void run{
re.m;//calling method of Reentrant class
}
};
t1.start;
}}Test it NowOutput: this is n method
this is m methodNext TopicJava io<<prevnext>> |
As per Sun Microsystems, in Java, monitors are reentrant, which implies that a Java thread can utilize the same monitor for various synchronized methods if one method is invoked from another method.
Advantage of Reentrant Monitor
It prevents the occurrence of deadlock in a single thread.
Let's explore the concept of the Java reentrant monitor through the following example:
class Reentrant {
public synchronized void m() {
n();
System.out.println("this is m() method");
}
public synchronized void n() {
System.out.println("this is n() method");
}
}
Within this particular class, there are two synchronized methods denoted as m and n. The method m invokes method n internally.
Next, we will invoke the m function on a thread. In the provided class, a thread is being created using an anonymous class.
public class ReentrantExample{
public static void main(String args[]){
final ReentrantExample re=new ReentrantExample();
Thread t1=new Thread(){
public void run(){
re.m();//calling method of Reentrant class
}
};
t1.start();
}}
Output: this is n() method
this is m() method