RAII and closures in Java


[This article originally appeared on my old metatechnology blog, back in February 2007]

One of the biggest reasons I still prefer C++ over newer brethren such as Java and C# is its support for RAII (Resource Acquisition Is Initialisation). Unlike C++, Java and C# have the finally construct, to give you a place to do clean up of resources. The trouble is this doesn't scale very well. If you have several resources in a scope you may have to nest try-catch-finally blocks. A good article describing this problem from a Java perspective is here.

Of course, in C# there is the using keyword, along with the IDisposable interface, which gives you a little more C++-like scoped disposal. Even this is less clean and more awkward than the C++ model, and I believe also has scalability problems (caveat - at time of writing I haven't really used this in real C# programs).

One way to work around the lack of deterministic destruction in such languages is to use the Execute-Around idiom (more detailed coverage in this pdf). This allows you to factor out the resource acquisition, initialisation and release code, from the code that uses the resource. It scales better than inline try-catch-finally, but can result in much more fragmented (using a named class) or messy (using an anonymous class) code. In some cases the fragmentation may be a good thing - after all Extract Method is a valuable refactoring tool. But at other times it may be too much, especially in such languages with a more imperative bias.

In languages with decent support for Closures, Execute-Around can be a much more natural and pleasant experience with less fragmentation (although more because of the side-effect of decent language syntax, than because of the formal benefits of closures).

But while C# has closures, as of .Net 2.0, Java doesn't. That is, not at the time of this writing. There are serious proposals afoot to add them to the language - and from the sound of this blog entry from Neal Gafter (former Java co-designer, now at Google),they should have all the features that make them useful for techniques such as Execute-Around (as well as a whole load of other benefits, of course, but you can read about this elsewhere - such as in the cited article).

Maybe there is hope yet for Java.


Please submit or upvote, here - or follow through to comment on Reddit