djechlin
djechlin

Reputation: 60768

Set Java exit code without exiting yet

In a highly concurrent program with lots of shutdown operations, wondering how to set the exit code without prematurely calling System.exit()? Possible to set an "execute this code when everything else is done" method? but I'd really just like to prematurely set the exit code.

Upvotes: 10

Views: 6688

Answers (4)

Tobias Ritzau
Tobias Ritzau

Reputation: 3327

Just store the result somewhere and use any suitable synchronization tool to tell that you are done. When you are done, just read the stored result and exit using System.exit(result).

I'm curious, if several threads set the result, which should you use?

Upvotes: 0

parsifal
parsifal

Reputation: 592

In a highly concurrent program with lots of shutdown operations

This is a code smell to me.

I can understand how multiple threads might want to shut down, but they shouldn't be allowed to do so.

Instead, I would create a global method called initiateShutdown(int code). This method would contain logic to determine when it's appropriate to actually shut down. Since you may not want a thread returning from this method, you could implement some sort of never-returning lock, and consign the thread to waiting on this lock.

Upvotes: 0

Cratylus
Cratylus

Reputation: 54074

If I understand correctly what you want is to somehow keep the exit code, run some methods and then call System.exit with the pre-decided exit code.
IMO what you should do is use Shutdown hooks instead. I.e. your code will run before the JVM shuts down and (if I got your requirement correctly) will have the same result with a straightforward coding implementation (i.e. instead of using using state variable and unusual coding logic to achieve what you are trying to do etc)

Upvotes: 3

Guido Anselmi
Guido Anselmi

Reputation: 3912

Have a master thread spawn off all other threads such that it only shuts down when all other threads are complete.

Upvotes: 1

Related Questions