views:

381

answers:

4

In C++ we have Resource Acquisition Is Initialization (RAII) pattern, which extremely simplify the 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 resource, when it's going 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).

+2  A: 

The nearest equivalent is try/finally, see http://java.sun.com/docs/books/tutorial/essential/exceptions/finally.html

Daniel Earwicker
+7  A: 

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

Tom Hawtin - tackline
+2  A: 

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

Kjetil Ødegaard
Which is just (useful) syntactic sugar for try/catch/finally. So if you want to get something done today (as opposed to 2011), see the answers about try/catch/finally.
John M
Except that try/finally sucks in comparison to RAII. The original question was whether Java had anything comparable to RAII, and the answer is, apparently, no.
David Thornley
+1  A: 

To many coders, the strength of the RAII idiom is that the life of the underlying resource is tied to a scope block, making things simpler to make and maintain; ultimately reducing errors from failing to release that resource.

Unfortunately you can't mimic this behaviour in Java as you can't create your own scope-bound structures. A language similar to Java that has tried to solve this problem is C#:

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

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

Perhaps we'll see functionality like this implemented in future.

jond
python added this as well with the `with` construct
hasen j