I'm using Executors.newScheduledThreadPool()
to create a ScheduledExecutorService
, specifying the number of threads like so:
int corePoolSize = 42;
ScheduledExecutorService foo = Executors.newScheduledThreadPool(corePoolSize);
According to the JavaDocs, the corePoolSize
argument sets
the number of threads to keep in the pool, even if they are idle.
Does this mean that this ExecutorService
implementation may create more than corePoolSize
threads as needed, similar to a cached thread pool?
ScheduledExecutorService: is an ExecutorService that can schedule tasks to execute after a given delay, or to execute periodically. Its key methods are schedule (), scheduleAtFixedRate () and scheduleWithFixedDelay (). You can create an executor by using one of several factory methods provided by the Executors utility class. Here’s to name a few:
Executors.newScheduledThreadPool (int numThreads) — A ScheduledExecutorService with a thread pool that is used to run tasks periodically or after a specified delay. Executors.newSingleThreadExecutor () — An ExecutorService with a single thread. Tasks submitted will be executed one at a time and in the order submitted.
Executors.newSingleThreadScheduledExecutor () — An ExecutorService that uses a single thread to execute tasks periodically or after a specified delay. The snippet below creates a fixed thread pool ExecutorService with a pool size of 2. I'll use this ExecutorService in the sections that follow.
The easiest way to create ExecutorService is to use one of the factory methods of the Executors class. For example, the following line of code will create a thread pool with 10 threads:
No. The correct answer is no, a ScheduledExecutorService will not spawn new threads.
See answer here
Does this mean that this ExecutorService implementation may create more than
corePoolSize
threads as needed?
Yes, that is exactly what it means. The reason for the existence of corePoolSize
is the expense of thread-creation. If you expect to be firing large numbers of short-lived tasks at your executor service, you may expect to find, at a given point in time, large numbers of idle threads.
Rather than have these threads die, only to be replaced a very short time later by newly-created threads, corePoolSize
will ensure that there will always be a number of spinning threads.
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