16

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 Answer 1

19

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.

1
  • 2
    I was assuming something like that, but good to have confirmation on that I don't have to change my logic or style, it's just a bug in the IDE.
    – icza
    Jun 7, 2014 at 5:58

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.