简体   繁体   English

ReentrantReadWriteLock(java)-在读取锁内嵌套写入锁

[英]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). 我在上面做的是使用ReentrantReadWriteLock,将锁“ lock”用于读取,然后在其中再次尝试获取用于写入的锁(在释放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 . 现在,他们都调用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. 这样他们就可以陷入僵局。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ReentrantReadWriteLock的性能读取锁定? - Performance of ReentrantReadWriteLock read lock? ReentrantReadWriteLock返回的锁是否等同于它的读写锁? - Is lock returned by ReentrantReadWriteLock equivalent to it's read and write locks? 文档与ReentrantReadWriteLock的矛盾。在公平模式下,最终写锁是否优先于读锁? - Documentation contradictions about ReentrantReadWriteLock. Does eventually write lock has priority over read lock or not in fair mode? ReentrantReadWriteLock上的读锁定是否足以同时读取RandomAccessFile - Is a read lock on a ReentrantReadWriteLock sufficient for concurrent reading of a RandomAccessFile java io读写锁 - java io read and write lock 是否有一个带有java监听器的读写锁? - Is there a read write lock with listeners for java? Java中的读/写锁实现 - Read/Write Lock implementation in Java Java读写锁定要求,具有来自不同线程的锁定和释放 - Java read & write lock requirement, with lock and release from different threads 为什么没有办法检查当前线程是否持有ReentrantReadWriteLock的读锁? - Why there is no way to check if current thread holds the read lock of ReentrantReadWriteLock? 如何检测谁持有公平 ReentrantReadWriteLock 的读锁? - How to detect who holds the read lock of fair ReentrantReadWriteLock?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM