16

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?

Matt Ball
  • 354,903
  • 100
  • 647
  • 710

2 Answers2

14

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

See answer here

Community
  • 1
  • 1
Michael
  • 304
  • 2
  • 8
  • Well sleuthed. I agree with your sentiment (in your deleted post) that this is kind of annoying. – Matt Ball Jul 26 '12 at 23:55
  • 1
    @Michael - Please explain why you think so. – AlikElzin-kilaka Feb 27 '17 at 20:20
  • Main reason is the following sentence from the [documentation](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ScheduledThreadPoolExecutor.html): "While this class inherits from ThreadPoolExecutor, a few of the inherited tuning methods are not useful for it. In particular, because it acts as a fixed-sized pool using corePoolSize threads and an unbounded queue, adjustments to maximumPoolSize have no useful effect." – AlikElzin-kilaka Feb 27 '17 at 20:34
6

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.

oxbow_lakes
  • 133,303
  • 56
  • 317
  • 449
  • The documentation! You either trust the documentation or you don't :-) – oxbow_lakes Jun 25 '12 at 21:27
  • 2
    Well, looks like this is not actually true. Need to look at the documentation for `ScheduledExecutorService`, not just `ThreadPoolExecutor`'s `corePoolSize` concept. Now I'm wondering why it's not called `minimumPoolSize`... – Matt Ball Jul 26 '12 at 23:56