Eclipse inconsistencies: Resource leak: '

2019-02-23 08:38发布

If I have the following code:

public OutputStream test(boolean condition) throws FileNotFoundException {
    return condition ? null : new FileOutputStream("test.txt");
}

Eclipse puts yellow squiggles under new FileOutputStream("test.txt") and shows me the following warning:

Resource leak: '<unassigned Closeable value>' is never closed

The strange thing is, if I remove the ternary operation:

public OutputStream test() throws FileNotFoundException {
    return new FileOutputStream("test.txt");
}

the warning goes away.

Is this an inconsistency (bug?) in Eclipse or am I missing some fundamental difference between the two scenarios?

In general, it seems like Eclipse is smart enough to understand that when I return a Closeable from a method, it is ok to not have the method close the stream (after-all, what's the point of returning a closed stream?). It even does this correctly when I return the result indirectly:

public OutputStream test() throws FileNotFoundException {
    FileOutputStream result = new FileOutputStream("test.txt");
    return result;
}

(no warnings here)

So, is Eclipse just getting confused by the ternary operation? If so, should I report this as a bug?


Another strange thing:

If I replace FileOutputStream with ByteArrayOutputStream, the warning goes away also:

public OutputStream test(boolean condition) {
    return condition ? null : new ByteArrayOutputStream();
}

How come it's treating these two streams differently? Both are direct descendents of OutputStream and implement the exact same interfaces (Closeable, Flushable, AutoCloseable). Does it somehow know that ByteArrayOutputStream.close() is a no-op? If so, is that hard-coded into Eclipse or does it actually parse the source or byte-code to figure this out?

0条回答
登录 后发表回答