This question already has an answer here:
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?
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).
If ReentrantLock wasn't reentrant you would deadlock at
get(index)
Suppose in a class you have two methods m1 and m2, both synchronized and m2 is calling m1. In that case if thread a has taken a lock on m1 and taking a lock again is not allowed then that thresad will keep on waiting for calling m2 (as it already has a the lock)
Consider this synchronized example. The same applies to lock but with more code.
The only way to avoid being re-entrant is to create locked and unlocked versions of each method. However what if you have two instances A and B. A calls B which calls A. How does B know not to call a synchronized method in A.
Some argue that reentrant locking should be avoided. In a critical section, you should know exactly what is going on. If a local critical section may call a foreign code that may call a local code back, that seems pretty complicated and potentially dangerous. It is better to have just a few well defined critical sections containing only local code.