views:

147

answers:

2

Hi,

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?

+3  A: 

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?

Jon Skeet
But you probably wouldn't want to.
Tom Hawtin - tackline
@Tom: True - it's not generally a good idea. Will edit.
Jon Skeet
+3  A: 

You need to own the lock to be able to unlock it. reentrantLockObject.isLocked() only is true if some thread owns the lock, not necessarily you.

  reentrantLockObject.lock();
  try{

       // do stuff
  }finally{
         reentrantLockObject.unlock();
  }

Here the thread owns the lock so they are able to unlock it.

John V.