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

I have a call to System.exit(1) in my multithreaded program. However, from time to time, instead of return code 1, the program exits with return code 0. I have no other calls to System.exit() , and I am sure that the program does not fail. What could be the reason, and how can I avoid this?

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

+4
source share
3 answers

Change your design for a more controlled shutdown.

There should be no expectation that calling System.exit() in an application with multiple threads will never cause a program to crash.

Instead of calling System.exit() to exit the program, you should send shutdown messages to each moving component and use Thread.join() to restore all threads you created. Your application must be able to close all parts in this way. The last command in the main thread should be to return the exit code. If you just call System.exit() , you leave all of this closing information for the JVM, which is just about to take a hard approach and kill everything in place.

Have you ever used Runtime.getRuntime.addShutdownHook() ? A call to System.exit() calls calls that can be set, and this can change the exit code.

+4
source

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

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

So maybe something is calling Runtime.halt(int) . In the final or finalizer?

+1
source

I think this is the only way that can happen if your JVM shuts down before System.exit(1) is executed. Do you think this is possible on your system?

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

Alternatively, as @Erick Robertson suggested, it is possible that something changes the exit status from the hook or something like that, although I'm not sure how this is possible.

Note: please ignore my previous comment. A call to System.exit(1) will terminate all currently running daemon / non-daemon threads.

0
source

Source: https://habr.com/ru/post/1334658/


All Articles