5

If I have the following code:

public OutputStream test(boolean condition) throws FileNotFoundException {
    return condition ? null : new FileOutputStream("test.txt");
}

Eclipse puts yellow squiggles under new FileOutputStream("test.txt") and shows me the following warning:

Resource leak: '<unassigned Closeable value>' is never closed

The strange thing is, if I remove the ternary operation:

public OutputStream test() throws FileNotFoundException {
    return new FileOutputStream("test.txt");
}

the warning goes away.

Is this an inconsistency (bug?) in Eclipse or am I missing some fundamental difference between the two scenarios?

In general, it seems like Eclipse is smart enough to understand that when I return a Closeable from a method, it is ok to not have the method close the stream (after-all, what's the point of returning a closed stream?). It even does this correctly when I return the result indirectly:

public OutputStream test() throws FileNotFoundException {
    FileOutputStream result = new FileOutputStream("test.txt");
    return result;
}

(no warnings here)

So, is Eclipse just getting confused by the ternary operation? If so, should I report this as a bug?


Another strange thing:

If I replace FileOutputStream with ByteArrayOutputStream, the warning goes away also:

public OutputStream test(boolean condition) {
    return condition ? null : new ByteArrayOutputStream();
}

How come it's treating these two streams differently? Both are direct descendents of OutputStream and implement the exact same interfaces (Closeable, Flushable, AutoCloseable). Does it somehow know that ByteArrayOutputStream.close() is a no-op? If so, is that hard-coded into Eclipse or does it actually parse the source or byte-code to figure this out?

Qix - MONICA WAS MISTREATED
  • 14,451
  • 16
  • 82
  • 145
Markus A.
  • 12,349
  • 8
  • 52
  • 116
  • Looks like this might be a bug in the static analysis. What version of Eclipse are you using? This was introduced in Eclipse 3.8/4.2 and got significantly better in 4.3 and there are more improvements coming in 4.4. So, make sure you are using the latest version. – Andrew Eisenberg May 05 '14 at 05:35
  • @AndrewEisenberg I'm using Kepler SR 1, which I believe, is v4.3.1. I filed a bug report with the Eclipse team: https://bugs.eclipse.org/bugs/show_bug.cgi?id=434065. There was a related bug (referenced there), which will be fixed in 4.4. Not sure if this fix will also address the issue here. – Markus A. May 05 '14 at 06:59
  • Your best chance is to download the latest 4.4 milestone and see if it is fixed. Since M7 is already out, things should be pretty stable and not much danger moving to it. – Andrew Eisenberg May 05 '14 at 15:47

1 Answers1

0

It is clearly a bug. The bug report https://bugs.eclipse.org/bugs/show_bug.cgi?id=434065 has been acknowledged, but not fixed.

The bug is still open as of July 2019.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216