...if executed from within a controller - in that case also 0 is returned as exit status sometimes.

I wrote a very small (single class) Spring-Boot app to reproduce the problem: https://github.com/drahkrub/spring-boot-exit-problem

Until recently, I thought it would be an interesting option to use different exit status of a Spring-Boot app (in production) for different follow up actions (backup, upgrade, restart, ...) but now I'm wondering whether this is really such a good idea...

Any thoughts on that?

(spring-boot 3.2.6, java 17)

Comment From: wilkinsona

This is just how the JVM works. You're calling System.exit() on a thread. That sets up a race between the JVM exiting normally with 0 as there are no non-daemon threads still running and with 42 because the System.exit() call won.

You can simulate this with the following main method:

    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            try {
                Thread.sleep(2000);
            }
            catch (InterruptedException ex) {
                Thread.currentThread().interrupt();
            }
            System.exit(42);
        });
        thread.setDaemon(true);
        thread.start();
    }

The sleep increases the chances that the JVM exiting normally will win the race. In fact, in my testing, it always does. If you remove the sleep, it will exit with 42.

Comment From: drahkrub

Hi @wilkinsona, thanks for the fast response and the clear explanation!

Surprisingly, on my computer even without sleep the program exits with 0 most of the time, I estimate in 90% of all runs.

But I understand the principle.

Does this mean that a certain exit status != 0 cannot be guaranteed (in Spring-Boot or Java at all) if the location (or place or thread or ...) where the shutdown is initiated is not restricted?

Comment From: wilkinsona

Does this mean that a certain exit status != 0 cannot be guaranteed (in Spring-Boot or Java at all) if the location (or place or thread or ...) where the shutdown is initiated is not restricted?

Yes, I believe so. Both the javadoc and the JLS are silent on what happens in a multi-threaded environment. If you want some clarity, a question on Stack Overflow may catch the attention of someone with the necessary JDK expertise.