views:

245

answers:

2

What is the best way to free resources (in this case unlock the ReadWriteLock) when leaving the scope ? How to cover all possible ways (return, break, exceptions etc)?

+10  A: 

A try/finally block is the closest thing that you can get to this behaviour:

Lock l = new Lock();
l.lock();  // Call the lock before calling try.
try {
    // Do some processing.
    // All code must go in here including break, return etc.
    return something;
} finally {
    l.unlock();
}
Michael Barker
"l.lock()" should really be called before "try" as per the example: http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/locks/Lock.html
McDowell
And to justify the prior comment: the reason you want to call l.lock() outside the try block is that lock() may throw an exception - and if it does, you definitely don't want to call unlock() on it (which will then throw an exception and make it hard to find the original exception throw).
Kevin Day
+2  A: 

Like mike said, a finally block should be your choice. see the finally block tutorial, where it is stated:

The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs.

dhiller