Java try finally variations
Posted
by Petr Gladkikh
on Stack Overflow
See other posts from Stack Overflow
or by Petr Gladkikh
Published on 2010-04-28T06:52:27Z
Indexed on
2010/04/28
7:03 UTC
Read the original article
Hit count: 290
This question nags me for a while but I did not found complete answer to it yet (e.g. this one is for C# http://stackoverflow.com/questions/463029/initializing-disposable-resources-outside-or-inside-try-finally). Consider two following Java code fragments:
Closeable in = new FileInputStream("data.txt");
try {
doSomething(in);
} finally {
in.close();
}
and second variation
Closeable in = null;
try {
in = new FileInputStream("data.txt");
doSomething(in);
} finally {
if (null != in) in.close();
}
The part that worries me is that the thread might be somewhat interrupted between the moment resource is acquired (e.g. file is opened) but resulting value is not assigned to respective local variable. Is there any other scenarios the thread might be interrupted in the point above other than:
- InterruptedException (e.g. via Thread#interrupt()) or OutOfMemoryError exception is thrown
- JVM exits (e.g. via kill, System.exit())
- Hardware fail (or bug in JVM for complete list :)
I have read that second approach is somewhat more "idiomatic" but IMO in the scenario above there's no difference and in all other scenarios they are equal.
So the question:
What are the differences between the two? Which should I prefer if I do concerned about freeing resources (especially in heavily multi-threading applications)? Why?
I would appreciate if anyone points me to parts of Java/JVM specs that support the answers.
© Stack Overflow or respective owner