[concurrency-interest] Locks with try/finally

Greg Gagne ggagne at westminstercollege.edu
Thu Jun 30 17:40:02 EDT 2005


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.


More information about the Concurrency-interest mailing list