I have a piece of code (simplified):
if(reentrantLockObject.isLocked()) {
reentrantLockObject.unlock();
}
where reentrantLockObject is java.util.concurrent.locks.ReentrantLock.
Sometimes I get IllegalMonitorStateException.
It seams that lock was released between check and unlock() call.
How can I prevent this exception?
isLockedreturns whether any thread holds the lock. I think you wantisHeldByCurrentThread:Having said that,
isHeldByCurrentThreadis documented to be mainly for diagnostic purposes – it would be unusual for this piece of code to be the right approach. Can you explain why you think you need it?