How to get locked/unlocked status of java.util.concurrent.locks.Lock

concurrency, java, locking, multithreading

Solution

You can use `tryLock()` to get the `Lock` if it's free.

`Lock` is an interface, so as long as all you need is any implementation of a `Lock`, then `ReentrantLock` has an `isLocked()` method; however, I am not certain why you would only want it if it is currently locked.

Make sure that this is not a case of the XY-Problem. Or are you just saying that you wouldn't need to unlock it if it were already unlocked?

Problem

Is there a way to get something like `isLocked` status of a Lock? What I am doing is acquiring a lock before a loop operation and releasing it only after a certain condition is met AND the lock is already locked. So I need it ask the lock if it is already locked and I can't seem to find a way in the API to do it.

Original source

Related problems