简体   繁体   中英

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.

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. Ie 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 (ie instead of using using state variable and unusual coding logic to achieve what you are trying to do etc)

让主线程产生所有其他线程,使其仅在所有其他线程完成时关闭。

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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM