I'm using Eclipse 4.2 with resource leak warnings enabled.
This code produces an, in my opinion false, resource leak warning.
public static void test(){
InputStream in = null;
try {
in = new FileInputStream("A");
} catch (IOException e) {
return;
}finally{
close(in);
}
}
public static void close(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
If I refactor the code, and pull the close method into the finally block, everything is fine.
public static void test2(){
InputStream in = null;
try {
in = new FileInputStream("A");
} catch (IOException e) {
return;
}finally{
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace()
}
}
}
}
Can I somehow remove these warnings without having to duplicate the code of the close
method and without having to disable the resource leak warnings?
I found a bug report here for something similar occuring in loops, but no loops exist in my code.
More details on the resource leak analysis can be found here - http://help.eclipse.org/juno/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2Ftasks%2Ftask-avoiding_resource_leaks.htm&cp=1_3_9_1
EDIT: A word on 'Resource leak' vs 'Potential resource leak'
Ideally we would want the compiler to give us the complete and correct set of problems, but there are limitations in achieving that :-)