Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a resource leak or a false positive?

Tags:

java

Eclipse gives me a warning on the declaration of "out". Is this a false positive?

Random r = new Random();
try(PrintWriter out1 = new PrintWriter("one.txt");
    PrintWriter out2 = new PrintWriter("two.txt"))
{
  PrintWriter out = r.nextBoolean()?out1:out2;
  out.println("x");
}

P.S.: The warning is "Resource leak: 'out' is never closed".

like image 757
Konrad Höffner Avatar asked Jun 07 '13 14:06

Konrad Höffner


People also ask

What is meant by resource leak?

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.

What does it mean resource leak is never closed?

@Borat - "resource leak" implies that some system resource (usually memory) is being lost or wasted needlessly. Usually this will impact you when you start getting OutOfMemoryErrors thrown during the normal operation of your program.


2 Answers

It's a false positive. All instances are correctly closed.

I turned off those resource-related warnings in Eclipse long ago. They're really not reliable as there are so many "obviously" correct control flow paths that cannot be identified as "correct" by Eclipse without actually executing them... Any non-trivial code will be doomed to have those false positives.

like image 115
Lukas Eder Avatar answered Nov 05 '22 16:11

Lukas Eder


It is definitely false positive, out is being assigned out1 or out2 which is being automatically closed. Furthermore out is not visible outside try block.

like image 23
Grzegorz Żur Avatar answered Nov 05 '22 14:11

Grzegorz Żur