简体   繁体   中英

Java Concurrency - Adding a Shutdown hook before calling `ExecutorService#execute`

I have a runnable thread MyDesiredRunnable which has the following run:

public void run() {
    try {
        this.process();
    } catch (InterruptedException e) {
        isAlive.set(false);
    }
}

isAlive is an AtomicBoolean .

The Scheduler:

// Class definition bla bla bla
   private final ExecutorService exth = Executors.newSingleThreadExecutor();

public void schedule() {
    Runnable r = new MyDesiredRunnable();
    Runnable sdt = ()->{MyDesiredRunnable.isAlive.set(false);};

    Runtime.getRuntime().addShutdownHook(new Thread(sdt));
    this.exth.execute(r);
}

This Scheduler will always be only one instance. My question is, "Does it matter if I add the shutdown hook before I call execute . All I can understand from javadocs is that the shutdown hook will not be resolved until JVM shutodown is commanded. Also, the execute command also doesn't seem to say anything against having a shutdown hook before/after. It's just that a few of ExecutorService examples on SO or even some books have the shutdownhook registration happening after we call execute. So I just wanted to know whether there is a "Catch" that I don't understand.

Thanks,

To avoid trying to detect if the task is running indirectly you can use the Thread itself. If the thread isn't alive, your task isn't running.

class ThreadedRunnable implements Runnable {
    volatile boolean started = false;
    volatile Thread thread;
    Runnable runnable;

    ThreadedRunnable(Runnable runnable) { this.runnable = runnable; }

    public void run() {
        thread = Thread.currentThread();
        started = true;
        try {
            runnable.run();
        } catch (Throwable t) { // don't silently discard it
            logger.error(runnable + " died", t);
        } finally {
            thread = null;
        }
    }

    public String state() { // or return an Enum
        Thread t = thread;
        return !started ? "not started" :
               t == null || !t.isAlive() ? "finished" : "running";
    }
}

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