1010import java .util .concurrent .ExecutorService ;
1111import java .util .concurrent .Executors ;
1212import java .util .concurrent .ScheduledExecutorService ;
13+ import java .util .concurrent .ScheduledThreadPoolExecutor ;
1314import java .util .concurrent .ThreadFactory ;
1415import java .util .concurrent .atomic .AtomicInteger ;
1516
@@ -41,12 +42,25 @@ public static ExecutorService newCachedThreadPool(String name) {
4142 /**
4243 * Creates a thread pool that can schedule commands to run after a given delay, or to execute periodically.
4344 *
45+ * <p>
46+ * Note:<br>
47+ * As we cancel scheduled tasks regularly, we want to get rid of cancelled tasks even with the penalty of the clean
48+ * up overhead, so the configure the created {@link ScheduledThreadPoolExecutor} with
49+ * {@link ScheduledThreadPoolExecutor#setRemoveOnCancelPolicy(boolean)}.
50+ * </p>
51+ *
4452 * @param corePoolSize the number of threads to keep in the pool, even if they are idle
4553 * @param name the thread pool name
4654 * @return a newly created scheduled thread pool
4755 */
4856 public static ScheduledExecutorService newScheduledThreadPool (int corePoolSize , String name ) {
49- return Executors .newScheduledThreadPool (corePoolSize , new ThreadFactoryWithNamePrefix (name ));
57+ ScheduledThreadPoolExecutor scheduledThreadPool = new ScheduledThreadPoolExecutor (corePoolSize , new ThreadFactoryWithNamePrefix (name ));
58+
59+ // as we cancel a lot we want to get rid of cancelled tasks
60+ // even with the penalty of the clean up overhead
61+ scheduledThreadPool .setRemoveOnCancelPolicy (true );
62+
63+ return scheduledThreadPool ;
5064 }
5165
5266 /**
@@ -61,7 +75,10 @@ public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize,
6175 * @return a newly created scheduled executor
6276 */
6377 public static ScheduledExecutorService newSingleThreadScheduledExecutor (String name ) {
64- return Executors .newSingleThreadScheduledExecutor (new ThreadFactoryWithNamePrefix (name ));
78+ // reuse our custom method which configures removal of cancelled tasks
79+ ScheduledExecutorService singleThreadScheduledExecutor = newScheduledThreadPool (1 , name );
80+
81+ return singleThreadScheduledExecutor ;
6582 }
6683
6784 /**
0 commit comments