I am a novice. I have written this piece of code and it shows that there is a resource leak there
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
What does it mean? Sorry for the naivety.
I am a novice. I have written this piece of code and it shows that there is a resource leak there
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
What does it mean? Sorry for the naivety.
What is happening is that you are never closing your Scanner, so that resource might be getting "leaked". What this means is that the JVM is allocating, deallocating, and managing objects (resources) behind the scenes and needs to know if your Scanner object is still being used, or if it can free the memory (do "garbage collection") to use for something else. When the resource is closed, you are letting the garbage collector know that those resources can be cleaned up. It is like opening a lot of yogurt containers and leaving them lying around the house. Are you still eating them or can they be put back in the fridge?
There are a few solutions for this. One is to explicitly call the close()
method on your Scanner as mentioned in the other answers. But there is another, cleaner way to manage resources.
In Java 7, a "try-with-resources" was introduced to auto-close resources like this because it was common for programmers to "forget" to close their resources. This makes it easier for the JVM to manage the resources for you.
try(Scanner scan = new Scanner(System.in))
{
int i = scan.nextInt();
}
catch(Exception e) {}
finally {}
An added benefit of using a try with resources is that it reminds the programmer to account for all the exceptional circumstances that may occur. For instance, what would happen if the user entered a character instead of an int
on the command line? What if something in your processing threw an exception and you forgot to close your Scanner on that branch of execution? The try-with-resources can simplify this and make the code more succinct and readable (if used properly).
This occurs because you haven't closed the scanner. Java Garbage collector manages just the memory so for other resources, you have to close them explicitly. Use
scan.close();
Hope it helps!!
Scanner
implements the Closeable
interface, which means that it should be closed at some point, that's why you are getting the warning. But I think you will find the answer you are looking for, for example here: Close a Scanner linked to System.in
You are never closing that resource after using it, the doc says that the scanner must be close
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".