简体   繁体   中英

How can I be sure a daemon thread is always running, in Java?

In a web app my code creates some daemon threads as inner classes to check some information from incoming requests.

    private static class AlertThread extends Thread {

    private AlertThread() {
        setDaemon(true);
    }

    public void run() {
        while (true) {
            try {
               ...
            }
            catch (InterruptedException e1) {
                LogFactory.getLog(AlertThread.class)
                        .warn("InterruptedException when waiting");
                e1.printStackTrace();
            }
            catch (Exception e) {
                mainLogger.error("Error processing Alert " + e.getMessage());
            }
        }
    }
}

Code works well, and thread is running fine, but I want to be sure that this thread will be always running, and if it is killed (by any unknown reason), how should I restart a new instance?

The best solution is to not let it die in the first place. You can do this

public void run() {
    while(true) {
        try {
          runOne();
        } catch(Throwable t) {
          // log t
        }
    }
}

This thread will not die unless you shutdown the application.

BTW You should make the thread a daemon before you start it and you should avoid extending Thread as doing so can lead to subtle bugs.

As your code is written, the while loop could be terminated by any Trowable that is not an Exception . It could be an Error such as a StackOverflowError for example.

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