开发者

What happens when a thread holding a lock with ReentrantReadWriteLock fails?

开发者 https://www.devze.com 2022-12-11 01:40 出处:网络
If the thread holding a ReentrantReadWriteLock.writeLock() stops executing due to an uncaught exception, is the lock released, or is it held and all the other threads 开发者_运维知识库are now deadlock

If the thread holding a ReentrantReadWriteLock.writeLock() stops executing due to an uncaught exception, is the lock released, or is it held and all the other threads 开发者_运维知识库are now deadlocked?


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.

If the thread used finally blocks properly, then it will have unlocked the writeLock on its way back up the stack.

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.

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. (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.

This is a key difference between using synchronized.

0

精彩评论

暂无评论...
验证码 换一张
取 消