In C++ we have the Resource Acquisition Is Initialization (RAII) pattern, which greatly simplifies resource management. The idea is to provide some wrapping object for any kind of resources. The wrapping object's destructor is then responsible for releasing the resources, when it goes out of its scope. For example:
{
auto_ptr<int> smartPointer = new int;
// some other code
} // the memory allocated for the int is released automatically
// by smartPointer's destructor
The most common usage are smart pointers. But, there are many other kinds of resources (files, mutexes, sockets, etc.) which can be managed exactly the same way.
In Java one doesn't have to bother the memory management. But all other types of resources remain. There is finally block, but its usage is quite inconvenient, especially when many different exceptions can be thrown.
So, my question is if there is any Java pattern which provides functionality equivalent to C++ RAII? If not, please share your best practices in this area (instead of the finally, unless it's used some sophisticated way).
You can use the usual acquire; try { use; } finally { release; }
. Alternatively you can abstract the resource handling with the Execute Around idiom.
Joshua Bloch has proposed adding a mechanism called Automatic Resource Management to Java as part of Project Coin (small language changes for JDK 7):
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With