Why would you recursively acquire a (reentrant) lock?

ReentrantLock allows a thread to acquire the same lock recursively, so that the lock count increases and decreases for subsequent locks / unlocks. If the lock value needs to be reduced to zero before it is released to other threads.

Why or under what circumstances will I write recursive recovery code?

The only thing I see in the presence of this function is to make it convenient for us to write recursive code, where the method (which acquires a lock during its execution) is called recursive.

Are there other situations where recursive / reacquisition of a lock by a thread might be useful?

Clarification of the question:

  • Please disregard the fact that blocking is reentrant. It just happens that the recursion is provided by a reenter lock.
  • I mean a recursive blocking function
  • Please do not answer why use reentrant lock.
  • Please do not answer "recursiveness is not the main feature of reentrant locking"
  • I want to know in what situations a recursive acquisition of a lock is required, whether the lock is reentrant or not.
+3


source to share


1 answer


You can also search better: it should be useful

Use case for blocking re-entry:

A (somewhat generic and contrived) example of an application for blocking re-entry might be:



  • You have some computation using an algorithm that intersects (maybe with loops in it). A traversal can visit the same node more than once due to loops or multiple paths to the same node.

  • The data structure is subject to concurrency and could be for some reason, possibly a different thread. You should be able to lock individual nodes to combat potential data corruption due to race conditions. For some reason (performance perhaps) you don't want to globally lock the entire data structure.

  • You cannot store complete information about which nodes you have visited or are using a data structure that does not allow "I've been here before" questions that need to be answered quickly.

  • An example of such a situation would be a simple implementation of Dijkstra's Algorithm with a priority queue implemented as a binary heap or breadth-first search using a simple linked list as the queue. In these cases, checking the queue for existing inserts is O (N) and you cannot do this on every iteration.

In this situation, keeping track of which locks you have already purchased is expensive. Assuming you want to do blocking on a node, the level of blocking re-entry mechanism makes it easier if you have visited a node before. You can just blindly block a node, perhaps unblock it after you pull it out of the queue.

+1


source







All Articles