Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoLock in Java - how to?

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

like image 914
Dmitry Khalatov Avatar asked Apr 18 '26 16:04

Dmitry Khalatov


1 Answers

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();
}
like image 160
Michael Barker Avatar answered Apr 21 '26 06:04

Michael Barker