user1061799
user1061799

Reputation: 95

ReentrantReadWriteLock - locking / releasing in if - else block

I have a question on ReadwriteLocks good practice. I've only ever used synchronized blocks before, so please bear with me.

Is the code below a correct way in which to use a ReadWriteLock? That is,

Obtain the lock in the private method.

If a condition is met, return from the private method having not released the lock. Release the lock in the public method.

Alternatively:

Obtain the lock in the private method.

If the condition is not met, release the lock immediately in the private method.

Many thanks

private List<Integer> list = new ArrayList<Integer>();

private ReadWriteLock listLock = new ReentrantReadWriteLock

public int methodA(int y) {
    ...........
    long ago = methodB(y);
    list.remove(y);
    listLock.writeLock().unlock();
}

private long methodB(int x) {
    listLock.writeLock().lock();
    if(list.contains(x) {
        long value = // do calculations on x
        return value;
    }
    else {
        listLock.writeLock().unlock();
        // return something else unconnected with list
    } 

Upvotes: 0

Views: 198

Answers (1)

Smith_61
Smith_61

Reputation: 2088

Normally when using locks you would do something similar to this.

Lock lock = ...; // Create type of lock
lock.lock();
try {
    // Do synchronized stuff
}
finally {
    lock.unlock();
}

This ensures that the lock is always unlocked at the end of the block. No matter if there is an exception thrown. Since you are using a reentrant lock you can place this in both methods and it will work correctly, not releasing the lock until the last finally block executes.

Edit: Javadocs for the Lock interface reinterates what I posted.

Upvotes: 4

Related Questions