Question

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.

Was it helpful?

Solution

  • You should be seeing a 'Potential resource leak...' warning, if not please open a bug.
  • The main issue here is that the compiler does not know what 'close(..)' method does. It may or may not close the resource. (Note that the compiler does not perform inter-procedural analysis)
  • You can choose to ignore 'Potential resource leak' warnings. ('Resource leak' warnings are guaranteed to be correct however the 'Potential... ' ones are not)

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'

  • The idea is that all reported 'Resource leak' warnings are guaranteed to be correct but may not be 'all' the resource leaks in the code base.
  • 'Potential resource leaks' are well... potential problems. Some developers turn on 'Potential...' warnings when they know something is going wrong but they do not know where. In such cases potential warnings help to narrow down the search. Some other developers just go over potential warnings from time to time to see if there is a real problem there.

Ideally we would want the compiler to give us the complete and correct set of problems, but there are limitations in achieving that :-)

OTHER TIPS

Good news: Eclipse 4.3 will recognise Google & Apache close utilities!

http://download.eclipse.org/eclipse/downloads/drops4/S-4.3M4-201212140730/news/

(Search "Leak analysis")

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top