Determine if Java `Lock` supports the current thread.

Suppose I have an instance of java.util.concurrent.locks.Lock

Is it possible to determine if the lock is held by the current thread?

Suppose a lock object implements the Lock interface and is not necessarily reentrant, so calling Lock or tryLock might not be the best way to check for a lock.

+6
source share
1 answer

The Lock interface itself does not provide such functionality, but its general constructor, ReentrantLock has this method: ReentrantLock.isHeldByCurrentThread() .

Please note, however, as indicated in the documentation, the main purpose of this method is to debug, approve, and test. If you need it for normal program logic, then perhaps there is a better solution.

+12
source

All Articles