java – Resource leak: in is never closed

java – Resource leak: in is never closed

Because you dont close your Scanner


As others have said, you need to call close on IO classes. Ill 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(;
    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 {

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( {

java – Resource leak: in is never closed

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

Leave a Reply

Your email address will not be published.