Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is C++ like resource management possible in Java [duplicate]

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

like image 649
oo_olo_oo Avatar asked Mar 26 '09 18:03

oo_olo_oo


2 Answers

You can use the usual acquire; try { use; } finally { release; }. Alternatively you can abstract the resource handling with the Execute Around idiom.

like image 112
Tom Hawtin - tackline Avatar answered Sep 21 '22 06:09

Tom Hawtin - tackline


Joshua Bloch has proposed adding a mechanism called Automatic Resource Management to Java as part of Project Coin (small language changes for JDK 7):

like image 28
Kjetil Ødegaard Avatar answered Sep 20 '22 06:09

Kjetil Ødegaard