16

为什么 Eclipse 会为以下代码发出奇怪的“资源泄漏:zin 永远不会关闭”警告,即使我使用try-with-resources

Path file = Paths.get("file.zip");
// Resource leak warning!
try (ZipInputStream zin = new ZipInputStream(Files.newInputStream(file))) {
    for (int i = 0; i < 5; i++)
        if (Math.random() < 0.5)
            throw new Exception();
} catch (Exception e) {
    e.printStackTrace();
}

如果我修改代码上的“任何内容”,警告就会消失。下面我列出了 3 个修改后的版本,它们都可以(没有警告)。


Mod #1:如果我for从块中删除循环try,警告就会消失:

// This is OK (no warning)
try (ZipInputStream zin = new ZipInputStream(Files.newInputStream(file))) {
    if (Math.random() < 0.5)
        throw new Exception();
} catch (Exception e) {
    e.printStackTrace();
}

Mod #2:如果我保留for循环但我删除了包装,也没有警告ZipInputStream

// This is OK (no warning)
try (InputStream in = Files.newInputStream(file))) {
    for (int i = 0; i < 5; i++)
        if (Math.random() < 0.5)
            throw new Exception();
} catch (Exception e) {
    e.printStackTrace();
}

Mod #3:如果我创建InputStream外部try-with-resources,也没有警告:

// This is also OK (no warning)
InputStream in = Files.newInputStream(file); // I declare to throw IOException
try (ZipInputStream zin = new ZipInputStream(in)) {
    for (int i = 0; i < 5; i++)
        if (Math.random() < 0.5)
            throw new Exception();
} catch (Exception e) {
    e.printStackTrace();
}

我使用 Eclipse Kepler (4.3.1) 但也使用 Kepler SR2 (4.3.2) 的结果相同。

4

1 回答 1

19

这似乎是 Eclipse 中的一个已知错误:[compiler][resource] Bad resource leak problem on return inside while loop(资源在 finally 块中传递

我自己也对此有所了解,并在跟踪器上添加了我的投票。

更新:上述错误已在 4.5 M7 中解决。这将包含在 Eclipse 4.5(“Mars”)的最终版本中 - 预计将于 2015 年 6 月 24 日发布。

于 2014-06-06T15:16:59.537 回答