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?
The ReentrantLock can also be operated in fair mode where the lock is granted to the longest waiting thread. Thus no thread experiences starvation and the variance in times to obtain the lock is also small. Without the fair mode the lock doesn't guarantee the order in which threads acquire the lock.
A ReentrantLock is owned by the thread last successfully locking, but not yet unlocking it. A thread invoking lock will return, successfully acquiring the lock, when the lock is not owned by another thread. The method will return immediately if the current thread already owns the lock.
An IllegalMonitorStateException is a runtime exception in Java that occurs in multithreaded applications. It indicates that the calling thread has attempted to wait on an object's monitor, or attempted to notify other threads waiting on an object's monitor, without owning the specified monitor.
What Is a Reentrant Lock? A reentrant lock is a mutual exclusion mechanism that allows threads to reenter into a lock on a resource (multiple times) without a deadlock situation. A thread entering into the lock increases the hold count by one every time. Similarly, the hold count decreases when unlock is requested.
isLocked
returns whether any thread holds the lock. I think you want isHeldByCurrentThread
:
if (reentrantLockObject.isHeldByCurrentThread()) {
reentrantLockObject.unlock();
}
Having said that, isHeldByCurrentThread
is 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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With