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 */
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With