I've always heard that resources in java must be closed after use or these resources will get exhausted. Is it really a matter of concern for small programs that use very few resources(like 1 or 2 file readers/ buffered readers and all)? Doesn't the JVM keep track of the resources being used by a program? And wouldn't it release all those resources once the program exits? If not, why would the JVM keep these resources blocked even after the program exit?
These resources are indeed closed upon a normal JVM exit. However, you may not always know how your method is being called, and it could perhaps be called 2000 times externally by another programmer, and those resources will start to stack up.
In addition, certain non-mainstream OSs may run into the issue that if the JVM were to halt abnormally(via Runtime.getRuntime().halt()
or a significant internal error/inconsistency within the JVM) then resources could remain open(due to cleanup code not being run), potentially unusable until rebooted or manually released. Even on mainstream systems sockets could remain open for multiple minutes.
When the process exits, the JVM exits. What happens then is that the OS will free up any resources previously used by the JVM. This includes things like memory, file handles etc.
Small programms might live with resource leaks, because the OS might handle this after the process ended. But this is considered non portable.
The bigger issue is that the OS the JVM is running in won't know how to free resources allocated on a remote machine or if there are even resources allocated that need to be freed.
It is not JVM but OS who releases resources allocated to the JVM process after it exited.
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