Search code examples
javamultithreadingreentrantlock

How is `hold count` value useful in Reentrant Lock?


Reentrant Lock ( https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReentrantLock.html ) has a feature to state the strength of locking by a particular Thread which is based on the value of 'hold count'. It is initilized when a Thread aquires the lock and each time when it re-aquires the lock the value is incremented. The value is decremented each time the thread invokes the unlock method on the lock.

Single thread at a time can be the owner of the Reentrant Lock hence simple boolen flag makes mcuh sense rather than an integers count. A thread already being the owner of the lock can only re-aquire it so count seams not of much. (any) use.

What is the usefulness of hold count ? What are the use cases of it ? One such use case can be to check of the current thread is holding the lock (hold count value > 0). But there are different APIs like isHeldByCurrentThread().


Solution

  • The API documentation for that method explains it :

    The hold count information is typically only used for testing and debugging purposes.

    So it's basically a method that can help you track down instances where your code fails to call unlock(). This is especially true for cases where you have reentrant usage of the lock.