The program finishes 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 (i.e. java process in eclipse for example) because it does not stop after a time limit in 9 seconds?
Best Answer
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:
Note the documentation of
newScheduledThreadPool(int corePoolSize)
:So, you have two possible ways to cause the JVM to terminate:
Pass
0
tonewScheduledThreadPool
instead of 1. The scheduler will not keep a live thread, and the JVM will terminate.Shut down the scheduler. You are supposed to do so anyway to release its resources. So change the
run
in your anonymousRunnable
to:(In fact, you don't need the
cancel
there - theshutdown
will take effect as soon as the next "beep" is completed.)