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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With