[英]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.