user3451476
user3451476

Reputation: 307

ScheduledExecutorService call shutdown for infinite scheduling

I am using a ScheduledExecutorService that would be scheduled to run every minute infinitely

Could some one tell me when to invoke the shutdown on the ScheduledExecutorService

I have already looked into Guava MoreExecutors. This does not work as I need to block the main thread to keep the other threads running continuously

Use case

I have a task that constantly monitors a system to check for latency/failures.

I need to run this task periodically and configure Cloudwatch alarms based on it. Ideally, I would want the task to continue executing even when there is a latency spike, because the alarm would have been triggered

So, I am using a ScheduledExecutorService to periodically schedule the tasks.

I want to know the ideal place where I would call shutdown() on the executor service

Upvotes: 1

Views: 1690

Answers (1)

Slaw
Slaw

Reputation: 45746

Currently, the factory methods in Executors return an instance of ScheduledThreadPoolExecutor1. By default, a ScheduledThreadPoolExecutor will not continue executing periodic tasks after it has been shutdown. You can configure this via setContinueExistingPeriodicTasksAfterShutdownPolicy.

Sets the policy on whether to continue executing existing periodic tasks even when this executor has been shutdown. In this case, executions will continue until shutdownNow or the policy is set to false when already shutdown. This value is by default false.

As it's really an implementation detail what implementation of ScheduledExecutorService the factory methods of Executors return, it's probably better to create a ScheduledThreadPoolExecutor directly.

ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
executor.setContinueExistingPeriodicTasksAfterShutdownPolicy(true);
executor.scheduleAtFixedRate(() -> System.out.println("Hello, World!"), 0L, 1L, TimeUnit.SECONDS);
executor.shutdown();

Note, this currently configures the ScheduledThreadPoolExecutor to use non-daemon threads. Even though shutdown was called, if the periodic tasks aren't cancelled they will keep the JVM alive. Use a custom ThreadFactory if you want to use daemon threads.


1. The newSingleThreadScheduledExecutor methods return a non-configurable wrapper that delegates to a ScheduledThreadPoolExecutor.

Upvotes: 1

Related Questions