Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.concurrent.ReentrantLock - why we want to acquire the same lock multiple times [duplicate]

I know if using ReentrantLock, it allows the same thread to acquire the same lock more than once. Internally, it has a counter to count the number of the lock acquisition. If you acquired the same lock twice, you would need to release it twice. But my question is that why would someone want to acquire the lock multiple times, should one time acquisition be enough? Can someone give me a common use case?

like image 978
Shengjie Avatar asked Sep 03 '13 15:09

Shengjie


1 Answers

Consider the following case in which you need a set of operations which isn't atomic, be atomic. For example you may want to set a value of an array but return its current value upon setting. (try-finally removed for brevity).

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){...}

If ReentrantLock wasn't reentrant you would deadlock at get(index)

like image 63
John Vint Avatar answered Oct 04 '22 00:10

John Vint