Ryan Sangha
Ryan Sangha

Reputation: 461

How to set ScheduledExecutorService to end when user quits program?

I have a ScheduledExecutorService that I pass a Runnable to. If the Enemy object that the thread is for dies, I end the thread with .shutDown(), which works just fine. However, if the user quits the program, the thread still runs. How I can shut it down when this happens?

ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    scheduler.scheduleAtFixedRate(runnable, 2,2, TimeUnit.SECONDS);


Runnable runnable = new Runnable() {
    @Override
    public void run() {
        System.out.println("SHOOT");
    }
};

Right now I'm overriding the stop()method in my Main from Application.

@Override
public void stop() throws Exception {

    Alert alert = new Alert(Alert.AlertType.CONFIRMATION, "Exit ?", ButtonType.YES, ButtonType.NO);
    alert.show();

    if (alert.getResult() == ButtonType.YES) {
        //this works if put outside of alert
        BlueSlime.scheduler.shutdown();
        super.stop();
    }

    if(alert.getResult() == ButtonType.NO){
        System.out.println("No");
    }

By making the scheduler static, I can shut it down by referencing BlueSLime from Main. This will shut it down, but is there a better way? Also the Alert doesn't really work, when I close the program, the Alert box shows for like half a second, and disappears and leaves the threads running again.

Upvotes: 1

Views: 1319

Answers (2)

mipa
mipa

Reputation: 10650

Don't use a shutdown hook. That's a brute force method. Instead make your threads daemon threads. Just add the following piece of code to your class

private static class DaemonThreadFactory implements ThreadFactory {
    public Thread newThread(Runnable r) {
        Thread thread = new Thread(r);
        thread.setDaemon(true);
        return thread;
    }
}

and then change your first line of code above to

ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1, new DaemonThreadFactory());

That's it.

Upvotes: 2

Guts
Guts

Reputation: 768

Add shutdown hook like this:

Runtime.getRuntime().addShutdownHook(new Thread(scheduler::shutdown))

Upvotes: 0

Related Questions