Strange “Resource leak: stream is never closed” with try-with-resources if Exception is thrown in a loop

半城伤御伤魂 提交于 2019-12-05 12:03:13

问题


Why is Eclipse giving a strange "Resource leak: zin is never closed" warning for the following code even though I use 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();
}

If I modify "anything" on the code, the warning goes away. Below I list 3 modified versions which are all OK (no warnings).


Mod #1: If I remove the for loop from the try block, the warning goes away:

// 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: Also no warning if I keep the for loop but I remove the wrapping 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: If I create the InputStream outside the try-with-resources, also no warning:

// 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();
}

I use Eclipse Kepler (4.3.1) but also the same result with Kepler SR2 (4.3.2).


回答1:


This appears to be a known bug in Eclipse: [compiler][resource] Bad resource leak problem on return inside while loop (resource passed on in finally block.

I just got bit by this myself, and have added my vote on the tracker.

Update: The above bug has been resolved in 4.5 M7. This will be included in the final release of Eclipse 4.5 ("Mars") - which looks on track to be released 2015-06-24.



来源:https://stackoverflow.com/questions/23294612/strange-resource-leak-stream-is-never-closed-with-try-with-resources-if-excep

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