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