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();
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.
You should close your Scanner when you're done with it:
If you are using JDK7 or 8, you can use try-catch with resources.This will automatically close the scanner.
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:
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:
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.
To remove the memory leak -
It is telling you that you need to close the Scanner you instantiated on
System.in
withScanner.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 theConsole
class.