-2

In this example:

private ReentrantReadWriteLock mLock = new ReentrantReadWriteLock();

public void method(boolean condition) {
    try {
        mLock.writelock.lock()

        if (condition) {
            mLock.writelock.unlock();
        }
    } finally {
        mLock.writelock.unlock();
    }
}

What happens when mLock.writelock.unlock() is called in the finally block if the unlock in the if statement has been executed?

Is this code safe or do I need to perform some check on whether there is a lock in place before attempting to unlock?

Kialandei
  • 394
  • 1
  • 11

1 Answers1

1

It seems very straight forward as per documentation, and it should throw IllegalMonitorStateException while re-executing ReentrantReadWriteLock.WriteLock.html#unlock.

Attempts to release this lock. If the current thread is the holder of this lock then the hold count is decremented. If the hold count is now zero then the lock is released. If the current thread is not the holder of this lock then IllegalMonitorStateException is thrown.

Documentation Link

Enforce condition on finally unlock execution also which would escape from exception.

Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103