Skip to main content

Suggestion: Resource aquisition is initialization.

2 replies [Last post]
galabar
Offline
Joined: 2005-02-01
Points: 0

In C++, the "resource acquisition is initialization" strategy is used, in part, to make sure that resources are properly deallocated. Java has a try {...} finally {...} mechanism to accomplish the same thing.

However, the problem with finally blocks is that they are possibly far away from where the resource is initialized. Here is an example:

FileInputStream in = new FileInputStream(...);

try {
...
}
finally {
try { in.close() } catch (Exception e) {}
}

As an enhancement, I propose the following syntax:

FileInputStream in = new FileInputStream(...);

final {
try { in.close(); } catch (Exception e) {}
}

These "final" blocks, similar to closures, could be placed anywhere within a block and would be run in reverse order from where they appear. So, you would get something similar to C++'s "resource acquisition is initialization" without having to introduce automatic variables. In addition, it would be superior to C++ in that you would not have to write a customer class to free a resource.

--Kevin

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
markf
Offline
Joined: 2005-01-20
Points: 0

I'm not sure if this really merits a new language construct. This can usually be dealt with by rethinking your design.

Bad:
[code]
try {
acquire resource;
....
operate on resource;
operate on resource some more;
....
lots of operations on resource;
...
} finally {
free resource;
}
[/code]Better:[code]
try {
acquire resource;
this.operateOn(resource);
} finally {
free resource;
}
[/code]Can you provide an example of a situation where there's no way to delegate cleanly? Is the super-long try block unavoidable for some reason?

tackline
Offline
Joined: 2003-06-19
Points: 0

Or:

acquire resource;
try {
use resoure;
} finally {
free resource;
}

We don't want to free a resource we have not acquired.