Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).

like image 225
oneCoderToRuleThemAll Avatar asked Jul 29 '19 19:07

oneCoderToRuleThemAll


2 Answers

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.

like image 148
Michał Krzywański Avatar answered Sep 27 '22 15:09

Michał Krzywański


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).

like image 36
Karol Dowbecki Avatar answered Sep 27 '22 15:09

Karol Dowbecki