简体   繁体   English

Spring - 让 TaskExecutor 和 TaskScheduler 由同一个线程池支持

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

I am a bean for TaskScheduler and TaskExecutor as following:我是 TaskScheduler 和 TaskExecutor 的 bean,如下所示:

@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? TaskExecutor 和 TaskScheduler 之间是否可以共享底层线程池执行器服务? Now I have twice a pool of each 10 fixed threads, but I would like to have one single pool of 20 threads.现在我有两个每个 10 个固定线程的池,但我想有一个 20 个线程的单个池。

These pools will be used for @Async, @Scheduled and @Retry annotatons.这些池将用于@Async、@Scheduled 和@Retry 注释。

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.但是,您可以实现自己的使用共享线程池的TaskExecutorTaskScheduler类。

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.请注意,尽管几个空闲线程不会对性能产生太大影响,因此除非您知道有两个池是主要的性能瓶颈,否则我不会浪费时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM