Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unlock on ReentrantLock without IllegalMonitorStateException

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?

like image 919
Mikhail Avatar asked May 11 '10 13:05

Mikhail


People also ask

Is reentrant lock thread safe?

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.

What is the reentrant 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.

What is illegal monitor state exception in Java?

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.

Is reentrant lock type?

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.


1 Answers

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?

like image 141
Jon Skeet Avatar answered Nov 10 '22 12:11

Jon Skeet