Sunday 3 April 2016

Synchronized block is Reentrant

A thread that has already acquired the lock of a synchronized block can freely enter another synchronized block, provided both synchronized blocks are locked on same object.

If a thread calls outer(), it can also call inner() from inside outer(), because both methods are synchronized on the same monitor object ("this")

 public class Reentrant{  
  public synchronized outer(){  
   inner();  
  }  
  public synchronized inner(){  
   //do something  
  }  
 }  


A customer lock can prevent reentrant. Now the thread calling outer() will be blocked at lock.lock() inside the inner() method.

 public class Lock{  
  private boolean isLocked = false;  
  public synchronized void lock()  
  throws InterruptedException{  
   while(isLocked){  
    wait();  
   }  
   isLocked = true;  
  }  
  public synchronized void unlock(){  
   isLocked = false;  
   notify();  
  }  
 }  

 public class NotReentrant{  
  Lock lock = new Lock();  
  public outer(){  
   lock.lock();  
   inner();  
   lock.unlock();  
  }  
  public synchronized inner(){  
   lock.lock();  
   //do something  
   lock.unlock();  
  }  
 }  


Reference: Locks in Java