Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why we should I close a java.util.Scanner variable? [duplicate]

Tags:

java

I got a warning in Eclipse with the following code:

Code:

Scanner money = new Scanner(System.in);
System.out.println(money.nextLine());
//money.close();

Warning:

Description Resource    Path    Location    Type
Resource leak: 'money' is never closed  apples.java /SwordsNMoney/src   line 6  Java P

What is this warning and what does 'Resource Leak' mean?

Thank you.

like image 350
Divyanshu Jimmy Avatar asked Nov 30 '22 19:11

Divyanshu Jimmy


2 Answers

Resource leak is generally an erroneous pattern of resource consumption where a program does not release the resource it has acquired. This can lead to poor services.

Garbage collection can only manage memory, not other system resources. If your Java program has plenty of free memory, garbage collection will not be triggered automatically.

All OSes have limits on the number of sockets, file handles, etc., that can be open. Thus, the unintentional maintenence of references to non-memory resources can lead to a resource leak. So it is extremely important to manage non-memory resources.

Classes which utilize non-memory resources should provide ways to explicitly allocate/deallocate those resources. We need to explictly call close() methods for deallocation of file descriptors in finally{}, as it will execute whether or not an exception is thrown.

like image 80
SparkOn Avatar answered Dec 09 '22 09:12

SparkOn


Scanner opens an underlying OS's file descriptor (or file channel, or stream), which typically is written in a non-managed(typically C language).

A stream kept open, can sometimes stay opened until the kernel decides to close it(like, after the program has completed execution... highly implementation dependent).

Hence its a good idea to close the resource explicitly.

like image 23
Aniket Inge Avatar answered Dec 09 '22 08:12

Aniket Inge