Reentrant Lock – Why we need to acquire a lock multiple times

Reentrant locks can be acquired multiple times. It maintains the number of times it has been acquired. Whenever acquired, it increments the counter and whenever released it decreases the count. Lock on that object is free only if this count is zero. But why do we need to acquire lock on same object multiple times within a piece of a code.
It can be if we have multiple code instructions which need to be accessed by a single thread.Here in setAndReturnPrevious method we acquire the lock and again acquire the lock inside set method because set method can be invoked explicitly also

final ReentrantLock lock = new ReentrantLock();
 
final Object[] objects = new Object[10]
public Object setAndReturnPrevious(int index, Object val){
   lock.lock();
      Object prev = get(index);
      set(index,val);
      return prev;
   lock.unlock();
}
public void set(int index, Object val){
    lock.lock();
         objects[index] = val;
    lock.unlock();
}
public Object get(index index){...}

Uday Ogra

Connect with me at http://facebook.com/tendulkarogra and lets have some healthy discussion :)

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *