简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM