Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing disposable resources outside or inside try/finally

I have seen two ways of acquiring and disposing resources. Either:

Resource resource = getResource();
try { /* do something with resource */ }
finally { resource.close(); }

or:

Resource resource = null;
try { resource = getResource(); /* do something with resource */ }
finally { if (resource != null) resource.close(); }

I was wondering which style is preferable. The first one avoids the if condition, while the second one (I presume) handles the case of thread abort right after the assignment but before entering the try block. What other pros and cons do these styles have over each other? Which one should I preferably use?

like image 736
Hosam Aly Avatar asked Jan 20 '09 20:01

Hosam Aly


1 Answers

In C#, just use the using statement:

using (Resource resource = GetResource())
{
    /* Do something */
}

This is the idiomatic way of cleaning up resources, and relies on the resource in question implementing the IDisposable interface. (Java now has a similar try-with-resources statement, for resources implementing AutoCloseable.)

There's no risk of a thread abort in Java happening between the assignment and entering the try block - aborts only occur during sleeps and waits. EDIT: I can't actually find this in the spec, which is somewhat worrying. Hmm.

like image 164
Jon Skeet Avatar answered Nov 15 '22 03:11

Jon Skeet