Spring - Have TaskExecutor and TaskScheduler backed by the same thread pool

我是研究僧i 提交于 2020-07-30 03:29:06

问题


I am a bean for TaskScheduler and TaskExecutor as following:

@Bean
public TaskScheduler taskScheduler() {
    ThreadPoolTaskScheduler s = new ThreadPoolTaskScheduler();

    s.setThreadNamePrefix("Task-Scheduler-");
    s.setPoolSize(10);
    s.setRemoveOnCancelPolicy(true);

    return s;
}

@Bean
public TaskExecutor taskExecutor() {
    ThreadPoolTaskExecutor e = new ThreadPoolTaskExecutor();

    e.setThreadNamePrefix("Task-Executor-");
    e.setMaxPoolSize(10);
    e.setCorePoolSize(10);

    return e;
}

Is it possible to share the underlying thread pool executor service between the TaskExecutor and the TaskScheduler? Now I have twice a pool of each 10 fixed threads, but I would like to have one single pool of 20 threads.

These pools will be used for @Async, @Scheduled and @Retry annotatons.


回答1:


You can't do this by using those two classes, because they are implementations that rely on an internal pool.

However, you can implement your own TaskExecutor and TaskScheduler class that use a shared ThreadPool.

Note though that a few idle threads is not going to have much of an impact on performance, so unless you know that having two pools is a major performance bottleneck, I wouldn't waste my time.



来源:https://stackoverflow.com/questions/42315164/spring-have-taskexecutor-and-taskscheduler-backed-by-the-same-thread-pool

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!