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();
}
}
}