简体   繁体   中英

Stop background thread when exception is thrown in main thread

I am writing a program in Java that uses a DDS mechanism for messaging that starts its own background threads when writers and the such are created. However if in the main thread an error occurs I throw an exception with the following code.

throw new FooUncheckedException(writerTypes.get(i) + " is not a writer type");

The main thread then terminates like it is supposed to. However, the background threads created by the DDS library I am using continue to run so the program never stops running technically. How would I go about gracefully shutting down the background threads as well that are keeping the program alive?

Before exiting the main thread, I would try cleaning up like this:

participant.delete_contained_entities(); 
DomainParticipantFactory.get_instance().delete_participant(participant);

[repeat for each participant you may have created...]

That should reclaim any resources (including threads) held/created by the participant.

What implementation of DDS are you using? If the DDS implementation you are using is implemented in native code, which is pretty typical, then the background threads created by the DDS library are native threads and you would not be able to make Java calls things like "setDaemon()" on them...

The mechanism described by C Tucker above is the standard DDS API to release all resources that the DDS middleware library creates for a given DomainParticipant so this should, among other things, terminate any internal threads the DDS implementation started. If it is not doing it I would consider is a bug in that particular DDS implementation.

Gerardo

If you set the daemon flag on the background threads before starting them, then they will be automatically killed when your main thread exits.

Thread t = new Thread(...);
t.setDaemon(true);
t.start();

A Java Virtual Machine will shut down and exit as soon as the last non-daemon thread dies. When your program first starts up, the main() thread is the only non-daemon thread.

"gracefully shutting down the background threads" will require the cooperation of those threads, ie they must provide some kind of API to request a shut down.

If it is ok to kill these threads instantly (without giving them the opportunity to finish what they are currently doing), and you want to terminate execution of the entire program, System.exit() may be the best choice. If you want to do this whenever an unhandled exception occurs, you can catch the exception in your main method:

try {
    doSomethingThatMightThrowAnException();
} catch (Throwable t) {
    reportError(t);
    System.exit();
}

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