All for Joomla All for Webmasters

Reentrant Monitor in Java

According to Sun Microsystems, Java monitors are reentrant means java thread can reuse the same monitor for different synchronized methods if method is called from the method.

Advantage of Reentrant Monitor

It eliminates the possibility of single thread deadlocking

Let’s understand the java reentrant monitor by the example given below:

  1. class Reentrant {
  2.     public synchronized void m() {
  3.     n();
  4.     System.out.println(“this is m() method”);
  5.     }
  6.     public synchronized void n() {
  7.     System.out.println(“this is n() method”);
  8.     }
  9. }

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.

  1. public class ReentrantExample{
  2. public static void main(String args[]){
  3. final ReentrantExample re=new ReentrantExample();
  4. Thread t1=new Thread(){
  5. public void run(){
  6. re.m();//calling method of Reentrant class
  7. }
  8. };
  9. t1.start();
  10. }}
Output: this is n() method
this is m() method
submit to reddit

Leave a Reply