Search code examples
javamultithreadingexitjava-6

System.exit(1) exists with return code 0 in multithreaded program


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.


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.