Eclipse不一致:资源泄漏:'<unassigned closeable =“”value =“”>'永远不会关闭</unassigned>

时间:2014-05-04 17:51:15

标签: java eclipse autocloseable

如果我有以下代码:

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

Eclipse将黄色波浪线放在new FileOutputStream("test.txt")下面,并向我显示以下警告:

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

奇怪的是,如果我删除了三元操作:

public OutputStream test() throws FileNotFoundException {
    return new FileOutputStream("test.txt");
}
警告消失了。

这是Eclipse中的不一致(错误吗?)还是我错过了两种情况之间的一些根本区别?

一般来说,似乎Eclipse足够聪明,可以理解当我从方法返回Closeable时,可以不让方法关闭流(总之,返回的重点是什么)封闭的流?)。当我间接返回结果时,它甚至可以正确地执行此操作:

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

(此处没有警告)

那么,Eclipse是否因为三元操作而感到困惑?如果是这样,我应该将此报告为错误吗?


另一件奇怪的事情:

如果我将FileOutputStream替换为ByteArrayOutputStream,警告也会消失:

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

为什么它对这两种流的处理方式不同?两者都是OutputStream的直接后代,并实现完全相同的接口(CloseableFlushableAutoCloseable)。它是否知道ByteArrayOutputStream.close()是无操作的?如果是这样,是硬编码到Eclipse中还是实际解析源代码或字节代码来解决这个问题?

1 个答案:

答案 0 :(得分:0)

这显然是一个错误。错误报告https://bugs.eclipse.org/bugs/show_bug.cgi?id=434065已得到确认,但尚未修复。

该bug到2019年7月仍未解决。

相关问题