tags:

views:

28

answers:

2

Hi all

I have a java program which has a server-socket listening infinitely. In case of JVM exiting abnormally through kill pid, what happens to system resources in this case, socket object ? Will the sockets be released or it will be locked up?

What is the best way to handle the cleanup of system resources like file descriptors/network-socket/jdbc connection, in case of abnormal JVM exit.

I know about finalizers, finally, but there is some amount of uncertainty and performance degradation using finalization.

Pls provide some ideas

+1  A: 

In the case of an abnormal exit, obviously the JVM can't do anything specifically to clean up whatever it has allocated. This responsibility would fall next to the operating system itself.

For sockets, modern operating systems will definitely release any sockets that had been opened by a process that crashes. The same applies to files and any other kernel objects (JDBC connections are implemented with some sort of socket).

Finalizers will not be run if the JVM terminates abnormally.

Greg Hewgill
Any possibilities of sensing the JVM crash and take the control to the code wherein I can cleanup the open sockets? Ofcourse, with finalizer option.
Also let me know which OS u mean, which will take care of auto-close of system resources upon process crash? I am running my appln in HP-UX 11.2.
@user309281: No, if the JVM is crashing then there is simply no way to run any further Java code inside the crashing process. The OS will clean up after you. I expect HP-UX will be robust in that regard.
Greg Hewgill
Any pointers/ref to OS doc about this auto-cleanup of locked system resources. My point was, for eg. if you consider port as a resource of the OS...if a process were to ensure that this resource is locked, it would need to do that by interacting with the OS...now, if the port is locked and the process were to die before releasing the lock... my question is if the OS would periodically remove these dead locks, thereby releasing the resources for other process to use...
@user309281: Please see this question and answer for a similar situation to yours: http://stackoverflow.com/questions/767292/how-do-i-close-a-port-in-a-case-of-program-termination
Greg Hewgill
Thank you so much. Your inputs were very valuable.
+1  A: 

System resources like memory, file descriptors, and network sockets are released when the JVM exits. Connections to the network sockets will take a while to close due to network protocols.

JDBC connections should be released once the database becomes aware that the other end of the connection has closed. Keep-alive timers can help cleanup the connection faster. The database will cleanup open transactions, and release locks as it cleans up the connections.

BillThor