srock
srock

Reputation: 413

ReentrantReadWriteLock (java) - nest write lock inside read lock

In the below code snippet, would it lead to a deadlock?

public class TestLocks {

ReadWriteLock lock = new ReentrantReadWriteLock();
public void add() {
    lock.readLock().lock();
    //code.....

    lock.writeLock().lock();
    //code
    lock.writeLock().unlock();

    //code....
    l.readLock().unlock();
}

What I'm doing above is using ReentrantReadWriteLock, lock 'lock' for reading and inside it again try to acquire lock for writing (before releasing the readLock). This might never be done in production but was curious to know if the above code would lead to a deadLock?

Upvotes: 5

Views: 4303

Answers (1)

David Schwartz
David Schwartz

Reputation: 182761

public void add() {
    lock.readLock().lock();
    //code.....

    lock.writeLock().lock();
    //code
    lock.writeLock().unlock();

    //code....
    l.readLock().unlock();
}

Consider if two threads both run this same code. After the first line, they both have the read lock. Now, they both call writeLock. Neither thread will release its read lock until it gets a write lock. But neither thread can get a write lock until the other releases its read lock. So they can deadlock.

Upvotes: 9

Related Questions