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

最后都变了- 提交于 2019-12-01 21:13:55

问题


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?


回答1:


It is clearly a bug. The bug report https://bugs.eclipse.org/bugs/show_bug.cgi?id=434065 has been acknowledged, but not fixed.

The bug is still open as of July 2019.



来源:https://stackoverflow.com/questions/23459568/eclipse-inconsistencies-resource-leak-unassigned-closeable-value-is-never

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!