问题
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