In C ++, we have the Resource Initialization (RAII) template , which greatly simplifies resource management. The idea is to provide some kind of wrapping object for any resources. Then the wrapper object's destructor is responsible for freeing resources when it goes out of scope. For example:
{
auto_ptr<int> smartPointer = new int;
}
The most common are smart pointers. But there are many other resources (files, mutexes, sockets, etc.) that can be controlled in exactly the same way.
In Java, there is no need to worry about memory management. But all other types of resources remain. There is a finally block , but its use is rather inconvenient, especially when many different exceptions can be thrown.
So my question is, is there any Java pattern that provides functionality equivalent to C ++ RAII? If not, please share your recommendations in this area (instead of ultimately, unless he used some complicated method).
source
share