views:

67

answers:

2

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?

+2  A: 

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

Andrzej Doyle
A: 

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.

Dani Cricco