Is it possible to use C ++ for resource management in Java

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;
    // some other code

} // the memory allocated for the int is released automatically
  // by smartPointer destructor

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

+5
source share
4 answers

You can use regular acquire; try { use; } finally { release; }. In addition, you can abstract resource processing with the Execute Around idiom .

+10
source

RAII , , ; , .

, Java, . , Java, , - #:

// explicit release
MyClass obj = MyClass();
obj.UseIt();
obj.Dispose();

// RAII-like (scope-bound) release
using(MyClass obj = new MyClass())
{
    obj.UseIt();
}

, , .

+1

All Articles