Is this a safe way to release resources in Java?
Posted
by palto
on Stack Overflow
See other posts from Stack Overflow
or by palto
Published on 2010-04-25T12:41:44Z
Indexed on
2010/04/25
12:43 UTC
Read the original article
Hit count: 211
java
Usually when code needs some resource that needs to be released I see it done like this:
InputStream in = null;
try{
in = new FileInputStream("myfile.txt");
doSomethingWithStream(in);
}finally{
if(in != null){
in.close();
}
}
What I don't like is that you have to initialize the variable to null and after that set it to another value and in the finally block check if the resource was initialized by checking if it is null. If it is not null, it needs to be released. I know I'm nitpicking, but I feel like this could be done cleaner.
What I would like to do is this:
InputStream in = new FileInputStream("myfile.txt");
try{
doSomethingWithStream(in);
}finally{
in.close();
}
To my eyes this looks almost as safe as the previous one. If resource initialization fails and it throws an exception, there's nothing to be done(since I didn't get the resource) so it doesn't have to be inside the try block. The only thing I'm worried is if there is some way(I'm not Java certified) that an exception or error can be thrown between operations?
Even simpler example:
Inputstream in = new FileInputStream("myfile.txt");
in.close();
Is there any way the stream would be left open that a try-finally block would prevent?
© Stack Overflow or respective owner