Resource leak: 'in' is never closed

JavaEclipseInputResourcesMemory Leaks

Java Problem Overview


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();

Java Solutions


Solution 1 - Java

Because you don't close your Scanner

in.close();

Solution 2 - Java

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)) {
    ... 
}

Solution 3 - Java

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.

Solution 4 - Java

// 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.

Solution 5 - Java

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: "));
    ...
}

Solution 6 - Java

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();
}

Solution 7 - Java

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.

Solution 8 - Java

You should close your Scanner when you're done with it:

in.close();

Solution 9 - Java

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.

Solution 10 - Java

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().

Solution 11 - Java

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.

Solution 12 - Java

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.

Solution 13 - Java

Scanner sc = new Scanner(System.in);

//do stuff with sc

sc.close();//write at end of code.

Solution 14 - Java

in.close();
scannerObject.close(); 

It will close Scanner and shut the warning.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1686995View Question on Stackoverflow
Solution 1 - JavanogardView Answer on Stackoverflow
Solution 2 - JavaEric LindauerView Answer on Stackoverflow
Solution 3 - JavaWillView Answer on Stackoverflow
Solution 4 - JavaAashiView Answer on Stackoverflow
Solution 5 - JavaAlexView Answer on Stackoverflow
Solution 6 - JavaagyeyaView Answer on Stackoverflow
Solution 7 - Javauser2393042View Answer on Stackoverflow
Solution 8 - JavaDan WView Answer on Stackoverflow
Solution 9 - JavaCharlie MartinView Answer on Stackoverflow
Solution 10 - JavaarshajiiView Answer on Stackoverflow
Solution 11 - JavaCarlos CambónView Answer on Stackoverflow
Solution 12 - JavazachdyerView Answer on Stackoverflow
Solution 13 - JavatejasView Answer on Stackoverflow
Solution 14 - JavaHRUTU.ZView Answer on Stackoverflow