Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doesn't the JVM release all the resources that are not explicitly closed by the programmer on program exit

Tags:

java

jvm

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?

like image 757
Albin Suresh Avatar asked Sep 06 '13 09:09

Albin Suresh


4 Answers

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.

like image 156
nanofarad Avatar answered Sep 29 '22 13:09

nanofarad


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.

like image 27
NPE Avatar answered Sep 29 '22 13:09

NPE


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.

like image 26
SpaceTrucker Avatar answered Sep 29 '22 12:09

SpaceTrucker


It is not JVM but OS who releases resources allocated to the JVM process after it exited.

like image 22
Evgeniy Dorofeev Avatar answered Sep 29 '22 14:09

Evgeniy Dorofeev