Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will a ScheduledExecutorService create new threads as needed?

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?

like image 320
Matt Ball Avatar asked Jun 25 '12 21:06

Matt Ball


People also ask

What is the use of scheduledexecutorservice?

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:

What is executors newscheduledthreadpool?

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.

What is newsinglethreadscheduledexecutor()?

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.

How do I create an ExecutorService?

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:


2 Answers

No. The correct answer is no, a ScheduledExecutorService will not spawn new threads.

See answer here

like image 161
Michael Avatar answered Oct 15 '22 15:10

Michael


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.

like image 42
oxbow_lakes Avatar answered Oct 15 '22 15:10

oxbow_lakes