Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if a Java `Lock` is held by the current thread

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

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

Assume the lock object only implements the Lock interface and is not necessarily reentrant, so calls to lock or tryLock may not be a good way to check the lock.

like image 390
arcyqwerty Avatar asked Mar 03 '16 16:03

arcyqwerty


1 Answers

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

Note however, as documentation says, the main purpose of this method is debugging, assertions and testing. If you need it for normal program logic, then probably there's some better solution.

like image 149
Tagir Valeev Avatar answered Oct 26 '22 23:10

Tagir Valeev