How to cancel a ScheduledFuture task from another task and gracefully complete it?

I play with ScheduledExecutorService. I want to make a simple ticker (one tick per second) and schedule another task later (after five seconds), which cancels the first one. And then block the main thread until everything is over, which should be after the completion of both tasks (+ - five seconds).

This is my code:

ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
Runnable tickTask = () -> System.out.println("Tick");
ScheduledFuture<?> scheduledTickTask = executor.scheduleAtFixedRate(tickTask, 0, 1, TimeUnit.SECONDS);
Runnable cancelTask = () -> scheduledTickTask.cancel(true);
executor.schedule(cancelTask, 5, TimeUnit.SECONDS);
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);

The problem that surprises me is that it is BLOCKS, as if there are still some running tasks. What for? cancelTaskshould end immediately, but scheduledTickTaskwas simply canceled, so what's the problem?

+4
source share
1

Javadoc ExecutorService.awaitTermination ( ):

, , , , , .

, shutdown, :

ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
Runnable tickTask = () -> System.out.println("Tick");
ScheduledFuture<?> scheduledTickTask = executor.scheduleAtFixedRate(tickTask, 0, 1, TimeUnit.SECONDS);
Runnable cancelTask = () -> {
    scheduledTickTask.cancel(true);
    executor.shutdown();
};
executor.schedule(cancelTask, 5, TimeUnit.SECONDS);
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);

- , "", .

+5

Source: https://habr.com/ru/post/1608674/


All Articles