oneCoderToRuleThemAll
oneCoderToRuleThemAll

Reputation: 865

What is the difference between a FixedThreadPool and ThreadPoolTaskExecutor?

Is there a difference between configuring a Thread pool using the following configurations:

Executors.newFixedThreadPool(50);

versus doing:

ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(50);
executor.setThreadNamePrefix("thread-pool");
executor.initialize();

I am not interested in configuring the thread pool during runtime (which is I think the main driver for using ThreadPoolTaskExecutor).

Upvotes: 11

Views: 3304

Answers (2)

Michał Krzywański
Michał Krzywański

Reputation: 16910

ThreadPoolTaskExecutor is a class from Spring Framework. On the other hand Executors::newFixedThreadPool creates a standard ThreadPoolExecutor thread pool that comes from standard Java and is available since Java 5.

From docs of ThreadPoolTaskExecutor :

JavaBean that allows for configuring a ThreadPoolExecutor in bean style (through its "corePoolSize", "maxPoolSize", "keepAliveSeconds", "queueCapacity" properties) and exposing it as a Spring TaskExecutor.

....

This class implements Spring's TaskExecutor interface as well as the Executor interface, with the former being the primary interface, the other just serving as secondary convenience. For this reason, the exception handling follows the TaskExecutor contract rather than the Executor contract, in particular regarding the TaskRejectedException.

Notice that ThreadPoolTaskExecutor implements many Spring interfaces like Aware, BeanNameAware, DisposableBean, InitializingBean which makes it easier to work with such pool as a Spring bean.

Also have a look at Karol Dowbecki's answer which correctly points out differences on those pools parameters.

Upvotes: 9

Karol Dowbecki
Karol Dowbecki

Reputation: 44952

In your example Spring's ThreadPoolTaskExecutor will create a ThreadPoolExecutor with corePoolSize of 50, maxPoolSize of Integer.MAX_VALUE and keepAlive of 60 seconds.

Meanwhile Executors.newFixedThreadPool(50) will set both corePoolSize and maxPoolSize to 50 and keepAlive of 0 seconds (see Java source code).

Upvotes: 8

Related Questions