It is mentioned in the Spring documentation that:
ThreadPoolTaskScheduler
actually implements Spring'sTaskExecutor
interface as well, so that a single instance can be used for asynchronous execution as soon as possible as well as scheduled, and potentially recurring, executions.
So which are the scenarios where we would want to use ThreadPoolTaskExecutor
instance over ThreadPoolTaskScheduler
instance?
I am using currently using Spring XML. I am creating bean of ThreadPoolTaskScheduler
as follows:
<task:scheduler id="myScheduler" pool-size="1"/>
while bean of ThreadPoolTaskExecutor
instance can be created as
<task:executor id="executor" pool-size="10"/>
ThreadPoolTaskExecutor is a java bean that allows for configuring a ThreadPoolExecutor in a bean style by setting up the values for the instance variables like corePoolSize, maxPoolSize, keepAliveSeconds, queueCapacity and exposing it as a Spring TaskExecutor.
ThreadPoolTaskScheduler ThreadPoolTaskScheduler is well suited for internal thread management, as it delegates tasks to the ScheduledExecutorService and implements the TaskExecutor interface – so that single instance of it is able to handle asynchronous potential executions as well as the @Scheduled annotation.
The default scheduler pool size in spring-boot is only one.
The TaskExecutor was originally created to give other Spring components an abstraction for thread pooling where needed. Components such as the ApplicationEventMulticaster , JMS's AbstractMessageListenerContainer , and Quartz integration all use the TaskExecutor abstraction to pool threads.
ThreadPoolTaskExecutor
is a specialized class for executing tasks.ThreadPoolTaskScheduler
is a specialized class for scheduling tasks.The sentence you quoted in the Spring documentation is only saying that you can use a scheduler to execute tasks, but that it is not its main purpose. A ThreadPoolTaskExecutor
provides fine-grained configuration over the thread pool through its corePoolSize
, maxPoolSize
, keepAliveSeconds
and queueCapacity
properties. A scheduler such as ThreadPoolTaskScheduler
does not provide such configuration.
As such, choosing between the two comes down the following question: do I need to execute or schedule execution of tasks?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With