1

I need to exclude web access from a ReentrantLock lock, see webAccess() method below. I can not add any parameter to webAccess() api because in real world it is our framework api that I am not supposed to change. To exclude webAccess from the lock, is it the safe way to use the ReentrantLock.isHeldByCurrentThread() method in webAccess()?

class X {
  ReentrantLock lock = new ReentrantLock();

  public mayLock(boolean shouldLock) {
    if (shouldLock) {
      lock.lock();
    }
    try {
      ...
      webAccess();
      ...
    } final {
      if (shouldLock) {
        lock.unlock();
      }
    }
  }

  public void webAccess() {
    boolean isLockedBySelf = lock.isHeldByCurrentThread();

    if (isLockedBySelf) {
      lock.unlock();
    }
    try {
       ... // web access here
    } finally {
       if (isLockedBySelf) {
         lock.lock();
       } 
    }
 }
Kai
  • 3,775
  • 10
  • 39
  • 54
  • 1
    Shouldn't you only re-take to lock if you had it to begin with? – Andreas Aug 21 '18 at 17:59
  • I want to release the lock at the beginning of webAccess() call because I don't want it to block other threads. I want to add the lock back after web access is done. – Kai Aug 21 '18 at 18:06
  • I don't know whether the lock has been taken or not in webAccess(), so I use lock.isHeldByCurrentThread() to check. – Kai Aug 22 '18 at 00:22

0 Answers0