Question

I have a call to System.exit(1) in my multi-threaded program. However from time to time instead of return code 1, the program exits with return code 0. I don't have any other calls System.exit() and I'm positive that the program doesn't exit cleanly. What can be the cause, and how can I avoid it?

Note that the error is intermittent and I cannot reproduce the same behavior in single threaded programs.

Was it helpful?

Solution

Modify your design to execute a more controlled shutdown.

There should be no expectation that calling System.exit() in an application with multiple threads would ever cause the program to exit cleanly.

Rather than calling System.exit() to leave the program, you should send shutdown messages to each moving component and use Thread.join() to recover any threads you created. Your application should be able to shut down all pieces nicely this way. The final command in the main thread should be to return your exit code. If you just call System.exit(), you're leaving all of these shut down details to the JVM, which is just going to take a heavy-handed approach and kill everything on the spot.

Have you used Runtime.getRuntime.addShutdownHook() at all? A call to System.exit() will invoke any shutdown hooks that may be installed and this could be changing the exit code.

OTHER TIPS

The documentation for Runtime.halt(int) says the following about its argument:

If the exit (equivalently, System.exit) method has already been invoked then this status code will override the status code passed to that method.

So perhaps something is invoking Runtime.halt(int). In a shutdown hook or finalizer?

I think the only way this may happen if your JVM terminates before System.exit(1) actually executed. Do you think this may be possible in your system?

Either, the code with System.exit(1) is being executed in a daemon thread, and so when all other live (non-daemon) threads finish working JVM exits cleanly (or not cleanly, as you can still get 0 exit code if you program throws an exception!)

Alternatively, as @Erick Robertson suggested, maybe something is modifying the exit status from a hook or something, although I am not sure how this is possible.

Note: please disregard my previous comment. Calling System.exit(1) will terminate all currently running daemon/non-daemon threads all-together.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top