[concurrency-interest] Locks with try/finally

David Holmes dholmes at dltech.com.au
Thu Jun 30 17:58:41 EDT 2005


Greg,

Yes it has been covered :)

Because if the lock() throws an exception you don't want to try to unlock()
a lock you don't own - which will probably throw a different exception that
replaces the first.

While it should be rare for a lock() to throw it may well be possible - such
as OutOfMemoryError. Imagine if the lock() were inside the try. Once in a
blue moon you run out of memory temporarily and start to throw
OutOfMemoryError. Your finally clause does an unlock() which (may) results
in  IllegalMonitorStateException being thrown** which replaces the OOME. You
thern try to figure out why once in a blue moon you are unlocking a lock you
don't own, oblivious to the underlying out-of-memory condition.

I actually made explicit mention of this at our (Joe Bowbeer and myself)
JavaOne talk today, as I've been asked about this by a couple of people.

** Hindsight: I'm no longer of the view that "borrowing" this exception was
the right choice to make. Ah well.

Cheers,
David Holmes

> -----Original Message-----
> From: concurrency-interest-bounces at cs.oswego.edu
> [mailto:concurrency-interest-bounces at cs.oswego.edu]On Behalf Of Greg
> Gagne
> Sent: Friday, 1 July 2005 7:40 AM
> To: concurrency-interest at altair.cs.oswego.edu
> Subject: [concurrency-interest] Locks with try/finally
>
>
> Hello all -
>
> I bet this has already been covered (many times) before, but in the
> API for ReentrantLock, it recommends the strategy of placing the code
> following the lock in a try-finally block, i.e.
>
> Lock lock = new ....
>
> lock.lock();
> try {
>      ... code that is run with the lock held
> }
> finally {
>      lock.unlock();
> }
>
> I understand why we want the unlock() should be in the finally clause
> (to ensure we release the lock), but why not put the lock() in the
> try as well? i.e.
>
> Lock lock = new ....
>
> try {
>      lock.lock();
>      ... code that is run with the lock held
> }
> finally {
>      lock.unlock();
> }
>
> Much thanks in advance for anyone who can enlighten me on this.
> _______________________________________________
> Concurrency-interest mailing list
> Concurrency-interest at altair.cs.oswego.edu
> http://altair.cs.oswego.edu/mailman/listinfo/concurrency-interest
>



More information about the Concurrency-interest mailing list