Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unassigned closeable stream

Tags:

java

stream

I'm working with Eclipse Juno and as I'm writing the following code, Eclipse warns me about a possible memory leak :

String s = new Scanner( System.in ).nextLine();

Indeed, I never close the System.in stream. How does the JVM (jre7) handle this ? Is it a good use ?

like image 988
Simon Avatar asked Jul 18 '26 14:07

Simon


1 Answers

This is a false alarm, I believe. Eclipse is confusing it with something like this:

String s = new Scanner(new FileReader("foo.txt")).nextLine();

which does leak a new Closeable each time you execute it.

But in your code, the underlying stream (System.in) is still reachable and usable. Certainly, there is no need to close it from the "resource leakage" perspective.


Indeed, I never close the System.in stream. How does the JVM (jre7) handle this ?

The System.in stream remains open until (presumably) the application exits. But that is no different to the situation if you hadn't called new Scanner(System.in) in the first place.

like image 181
Stephen C Avatar answered Jul 21 '26 02:07

Stephen C