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?
In C#, just use the using statement:
using (Resource resource = GetResource())
{
/* Do something */
}
Or since C# 8.0 you also have the option of the using declaration which is like the above but implicitly spans to the end of the current scope:
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.