Why does Eclipse give me the warming "Resource leak: 'in' is never closed" in the following code?
public void readShapeData() {
Scanner in = new Scanner(System.in);
System.out.println("Enter the width of the Rectangle: ");
width = in.nextDouble();
System.out.println("Enter the height of the Rectangle: ");
height = in.nextDouble();
@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.
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.
In general, a Java memory leak happens when an application unintentionally (due to logical errors in code) holds on to object references that are no longer required. These unintentional object references prevent the built-in Java garbage collection mechanism from freeing up the memory consumed by these objects.
Because you don't close your Scanner
in.close();
As others have said, you need to call 'close' on IO classes. I'll add that this is an excellent spot to use the try - finally block with no catch, like this:
public void readShapeData() throws IOException {
Scanner in = new Scanner(System.in);
try {
System.out.println("Enter the width of the Rectangle: ");
width = in.nextDouble();
System.out.println("Enter the height of the Rectangle: ");
height = in.nextDouble();
} finally {
in.close();
}
}
This ensures that your Scanner is always closed, guaranteeing proper resource cleanup.
Equivalently, in Java 7 or greater, you can use the "try-with-resources" syntax:
try (Scanner in = new Scanner(System.in)) {
...
}
You need call in.close()
, in a finally
block to ensure it occurs.
From the Eclipse documentation, here is why it flags this particular problem (emphasis mine):
Classes implementing the interface java.io.Closeable (since JDK 1.5) and java.lang.AutoCloseable (since JDK 1.7) are considered to represent external resources, which should be closed using method close(), when they are no longer needed.
The Eclipse Java compiler is able to analyze whether code using such types adheres to this policy.
...
The compiler will flag [violations] with "Resource leak: 'stream' is never closed".
Full explanation here.
It is telling you that you need to close the Scanner you instantiated on System.in
with Scanner.close()
. Normally every reader should be closed.
Note that if you close System.in
, you won't be able to read from it again. You may also take a look at the Console
class.
public void readShapeData() {
Console console = System.console();
double width = Double.parseDouble(console.readLine("Enter the width of the Rectangle: "));
double height = Double.parseDouble(console.readLine("Enter the height of the Rectangle: "));
...
}
// An InputStream which is typically connected to keyboard input of console programs
Scanner in= new Scanner(System.in);
above line will invoke Constructor of Scanner class with argument System.in, and will return a reference to newly constructed object.
It is connected to a Input Stream that is connected to Keyboard, so now at run-time you can take user input to do required operation.
//Write piece of code
To remove the memory leak -
in.close();//write at end of code.
If you are using JDK7 or 8, you can use try-catch with resources.This will automatically close the scanner.
try ( Scanner scanner = new Scanner(System.in); )
{
System.out.println("Enter the width of the Rectangle: ");
width = scanner.nextDouble();
System.out.println("Enter the height of the Rectangle: ");
height = scanner.nextDouble();
}
catch(Exception ex)
{
//exception handling...do something (e.g., print the error message)
ex.printStackTrace();
}
adding private static Scanner in;
does not really fix the problem, it only clears out the warning.
Making the scanner static means it remains open forever (or until the class get's unloaded, which nearly is "forever").
The compiler gives you no warning any more, since you told him "keep it open forever". But that is not what you really wanted to, since you should close resources as soon as you don't need them any more.
HTH, Manfred.
Okay, seriously, in many cases at least, this is actually a bug. It shows up in VS Code as well, and it's the linter noticing that you've reached the end of the enclosing scope without closing the scanner object, but not recognizing that closing all open file descriptors is part of process termination. There's no resource leak because the resources are all cleaned up at termination, and the process goes away, leaving nowhere for the resource to be held.
You should close your Scanner when you're done with it:
in.close();
Generally, instances of classes that deal with I/O should be closed after you're finished with them. So at the end of your code you could add in.close()
.
The Scanner should be closed. It is a good practice to close Readers, Streams...and this kind of objects to free up resources and aovid memory leaks; and doing so in a finally block to make sure that they are closed up even if an exception occurs while handling those objects.
private static Scanner in;
I fixed it by declaring in as a private static Scanner class variable. Not sure why that fixed it but that is what eclipse recommended I do.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With