Determines whether the current thread holds Java ` lock`

Suppose I have a Java util. concurrent. locks. Instance of lock

Can I determine whether the current thread holds a lock?

Assuming that the lock object only implements the lock interface and is not necessarily reentrant, calling lock or trylock may not be a good way to check the lock

Solution

The lock interface itself does not provide such a function, but its common implementer reentrantlock has such a method: reentrantlock isHeldByCurrentThread().

Note, however, that the main purpose of this method is debugging, assertion, and testing, as described in the documentation If you need it for normal program logic, there may be some better solutions

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>