简体   繁体   中英

Stopping a Java service with many threads running

I have a Java service that is multi-threaded. This a publisher-subscriber application.

There is a message bus and there are several plugin components listening to the message bus. Each request from a plugin is handled by the message bus in a separate thread. It runs as a Windows service.

In the stop method, currently what I am doing is calling System.exit(0) . In several other similar questions, some people have said it to be a bad practice, while some others claim that it is fine. Even Sonarqube complains about it.

So what it is the graceful way to stop all these threads? Should I call Thread.interrupt on them?

These clients are continuously listening to the message bus and if any event messages are received they process it.

Using Thread.interrupt() is a perfectly acceptable way of doing this. The reason being that if you're in an interruptable blocking call (like Thread.sleep or using java.nio Channel operations), you'll actually be able to break out of those right away.

More details on this SO question and here

For more detailed explanations visit: here

Summary:

  • thread.interrupt() does not stop a thread. It is used for coordination in multi-threaded programs. Don't use it unless you know exactly what you do.
  • Throwing a RuntimeException will (usually) terminate the thread but not necessarily the program.
  • System.exit(int) almost always terminates the program and returns a status code.
  • In unusual situations, System.exit(int) might not actually stop the program.
  • Runtime.getRuntime().halt(int) on the other hand, always does.

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