«Back to Home

Core Java

Topics

Reentrant Monitor In Java

Reentrant Monitor
 
In Java, monitors are reentrant which means Java, thread can reuse the same monitor for different synchronized methods, but the method is called from the method.
 
Advantage of Reentrant Monitor

Reentrant monitor eliminates the possibility of the single thread deadlocking.
 
Let's see an example of the reentrant monitor, given below.
 
Code
  1. class ReentrantMonitorEx {  
  2.     public synchronized void a() {  
  3.         b();  
  4.         System.out.println(" a() method");  
  5.     }  
  6.     public synchronized void b() {  
  7.         System.out.println(" b() method");  
  8.     }  
  9. }  
  10. public class Example1 {  
  11.     public static void main(String args[]) {  
  12.         final Example1 e = new Example1();  
  13.         Thread t1 = new Thread() {  
  14.             public void run() {  
  15.                 new ReentrantMonitorEx().a();  
  16.             }  
  17.         };  
  18.         t1.start();  
  19.     }  
  20. }  
35
 
Output

36

In the example, mentioned above, a and b are the synchronized methods. The a() method internally calls the b() method and we create thread, using annonymous class to call the a() method on a thread.
 
Summary

Thus, we learnt that Reentrant monitor eliminates the possibility of a single thread deadlocking and also learnt how to create it in Java.