Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resource leak: 'in' is never closed

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();
like image 363
user1686995 Avatar asked Sep 20 '12 19:09

user1686995


People also ask

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.

What is meant by a 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 resource leak in Java mean?

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.


12 Answers

Because you don't close your Scanner

in.close();
like image 129
nogard Avatar answered Oct 01 '22 16:10

nogard


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)) {
    ... 
}
like image 35
Eric Lindauer Avatar answered Oct 01 '22 18:10

Eric Lindauer


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.

like image 22
Will Avatar answered Oct 01 '22 17:10

Will


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: "));
    ...
}
like image 21
Alex Avatar answered Oct 01 '22 17:10

Alex


// 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.
like image 27
Aashi Avatar answered Oct 01 '22 17:10

Aashi


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();
}
like image 44
agyeya Avatar answered Oct 01 '22 18:10

agyeya


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.

like image 22
user2393042 Avatar answered Oct 01 '22 18:10

user2393042


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.

like image 5
Charlie Martin Avatar answered Oct 01 '22 18:10

Charlie Martin


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

in.close();
like image 3
Dan W Avatar answered Oct 01 '22 18:10

Dan W


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

like image 2
arshajii Avatar answered Oct 01 '22 17:10

arshajii


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.

like image 1
Carlos Cambón Avatar answered Oct 01 '22 17:10

Carlos Cambón


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.

like image 1
zachdyer Avatar answered Oct 01 '22 17:10

zachdyer