How to stop a ScheduledExecutorService?

天大地大妈咪最大 提交于 2019-11-30 12:45:31

The issue you have is that the scheduler keeps a live thread around after you have cancelled the beep task.

If there is a live non-daemon thread, the JVM stays alive.

The reason that it keeps this thread around is that you have told it to do so in this line:

private final ScheduledExecutorService scheduler
        = Executors.newScheduledThreadPool(1);

Note the documentation of newScheduledThreadPool(int corePoolSize):

corePoolSize - the number of threads to keep in the pool, even if they are idle.

So, you have two possible ways to cause the JVM to terminate:

  1. Pass 0 to newScheduledThreadPool instead of 1. The scheduler will not keep a live thread, and the JVM will terminate.

  2. Shut down the scheduler. You are supposed to do so anyway to release its resources. So change the run in your anonymous Runnable to:

    public void run() {
        beeperHandle.cancel(true);
        scheduler.shutdown();
    }
    

(In fact, you don't need the cancel there - the shutdown will take effect as soon as the next "beep" is completed.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!