简体   繁体   English

用ReentrantReadWriteLock持有锁的线程失败时会发生什么?

[英]What happens when a thread holding a lock with ReentrantReadWriteLock fails?

如果由于未捕获的异常而持有ReentrantReadWriteLock.writeLock()的线程停止执行,则释放该锁,还是保持该锁,而所有其他线程现在都死锁了?

I'll assume that by "fail", you mean an uncaught exception propagates off the top of the Thread's run method, causing it to stop executing. 我假设“失败”是指未捕获的异常从Thread的run方法的顶部传播,导致其停止执行。

If the thread used finally blocks properly, then it will have unlocked the writeLock on its way back up the stack. 如果finally使用的线程正常阻塞,则它将在备份堆栈的途中解锁writeLock

If the thread didn't call unlock() , however, it still holds that monitor even though it's not running any more - so yes, other threads will be deadlocked. 但是,如果线程没有调用unlock() ,即使它不再运行,它仍然保留该监视器-因此,是的,其他线程将被死锁。

This is why it's critical important to acquire and release resources correctly. 这就是为什么正确获取和释放资源至关重要的原因。 And also a reason to stick with synchronized blocks unless/until you can establish that you need the functionality of specific locks - because they cannot fail to be released. 这也是坚持使用synchronized块的一个原因,除非/直到您可以确定需要特定锁的功能-因为它们一定不会被释放。 (In your case I'm sure you do need the separate read/write locks, I'm making a more general point here.) (在您的情况下,我确定您确实需要单独的读/写锁,在这里我要提出一个更一般的观点。)

You must use a try-finally block when using "Explicit Lock", to release any lock that you acquired. 使用“显式锁定”时,必须使用try-finally块来释放您获得的任何锁定。

This is a key difference between using synchronized. 这是使用同步之间的主要区别。

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

相关问题 线程无法获得锁定会发生什么? - What happens to a Thread that fails to acquire a lock? ReentrantReadWriteLock即使状态为Unlocked也无法获得锁定 - ReentrantReadWriteLock fails to get lock even when its state is Unlocked 当多个线程想要访问ReentrantReadWriteLock时会发生什么? - what happens when multiple threads want to access a ReentrantReadWriteLock? 不等待锁的线程中断时会发生什么 - What happens when interrupt on thread which does not waiting for a lock 线程在同步块内崩溃时锁定会发生什么? - What happens to the lock when thread crashes inside a Synchronized block? 使用 ReentrantReadWriteLock 时需要降级锁 - is lock downgrading necessary when using ReentrantReadWriteLock 无法获取信号量的线程会怎样? - What happens to a Thread that fails to acquire a Semaphore? 为什么没有办法检查当前线程是否持有ReentrantReadWriteLock的读锁? - Why there is no way to check if current thread holds the read lock of ReentrantReadWriteLock? 如果一个线程试图获取一个它已经持有的锁会发生什么? - What happens if a thread tries to acquire a lock that it already holds? JPA-悲观锁-锁存在时会发生什么? - JPA - Pessimistic Lock - What happens when the lock exists?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM