Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 962
icza Avatar asked Apr 25 '14 13:04

icza


People also ask

What is resource leak error?

In computer science, a resource leak is a particular type of resource consumption by a computer program where the program does not release resources it has acquired. This condition is normally the result of a bug in a program.


Video Answer


1 Answers

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.

like image 56
ziesemer Avatar answered Sep 22 '22 13:09

ziesemer