How to stop ScheduledExecutorService?

The program ends after nine prints:

class BeeperControl { private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); public void beep() { final Runnable beeper = new Runnable() { public void run() { System.out.println("beep"); } }; final ScheduledFuture<?> beeperHandle = scheduler.scheduleAtFixedRate( beeper, 1, 1, SECONDS); scheduler.schedule(new Runnable() { public void run() { beeperHandle.cancel(true); } }, 1 * 9, SECONDS); } public static void main(String[] args) { BeeperControl bc = new BeeperControl(); bc.beep(); } } 

How to stop a process (for example, a java process in eclipse, for example) because it does not stop after a period of 9 seconds?

+8
java executorservice
source share
1 answer

The problem is that the scheduler maintains a live stream after you cancel the audio task.

If there is a live stream without a demon, the JVM stays alive.

The reason he supports this thread is because you told him to do this on this line:

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

Check out the newScheduledThreadPool(int corePoolSize) documentation:

corePoolSize - the number of threads to store in the pool, even if they do not work.

So, you have two possible ways: the JVM may terminate:

  • Pass 0 to newScheduledThreadPool instead of 1. The scheduler will not support the live thread, and the JVM will newScheduledThreadPool .

  • Complete the scheduler. You still have to do this to free up your resources. Therefore, change run in anonymous Runnable to:

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

(Actually, you don’t need cancel - shutdown takes effect as soon as the next β€œbeep” is completed.)

+11
source share

All Articles