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
2008-09-30 06:05:11
"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
2008-09-30 13:11:00
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
2008-10-01 03:54:49
+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
2008-09-30 06:20:14