multithreading - java.concurrent.ReentrantLock - why we want to acquire the same lock multiple times -


this question has answer here:

i know if using reentrantlock, allows same thread acquire same lock more once. internally, has counter count number of lock acquisition. if acquired same lock twice, need release twice. question why want acquire lock multiple times, should 1 time acquisition enough? can give me common use case?

consider following case in need set of operations isn't atomic, atomic. example may want set value of array return current value upon setting. (try-finally removed 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 deadlock @ get(index)


Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -