Question

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).

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top