Monday, February 02, 2009

Deadlock while terminating JVM - how to avoid it

Quite recently I was implementing some very small command line tool in Java. In order to clean and release all resources in case user presses Ctrl+C I added shutdown hooks. Unfortunately by mistake I added:

System.exit(0);

line within the shutdown hook and my application couldn't close. When I used jps and jstack I saw a deadlock on exit() method? WTF - I thought - I assumed that this method tries to forcibly close the JVM. You now know what was the problem?

If you read documentation carefully you should know :)

If this method is invoked after the virtual machine has begun its shutdown sequence then if shutdown hooks are being run this method will block indefinitely. If shutdown hooks have already been run and on-exit finalization has been enabled then this method halts the virtual machine with the given status code if the status is nonzero; otherwise, it blocks indefinitely.

This explains everything.

Conclusions - never invoke System.exit() from shutdown hooks and READ javadoc even if you're absolutely sure you know Java well...

2 comments:

David Hofmann said...

Jaja, this is really nice though.
From my point of view System.exit should simply detect if it is being called twice but well ... backwards compatibility ....

SBL - Java technologies said...

Useful post...

Regards, SBL - Java technologies </a