Why does ScheduledThreadPoolExecutor only accept a fixed number of threads?

Matthew picture Matthew · Jul 28, 2010 · Viewed 8.5k times · Source

I may imagine some tasks scheduled to take a very long time and ScheduledThreadPoolExecutor would create additional threads for the other tasks that need to be run, until a maximum number of threads is reached.

But seems that I can only specify a fixed number of threads for the pool, why is that so ?

Answer

extraneon picture extraneon · Jul 28, 2010

As the why, I don't know either. But I can imagine.

The amount of resources of a computer is limited. Not all resources can be handled concurrently either.

If multiple processes concurrently load files, they will be loaded slower than if they were being loaded sequentially (at least on a harddisk).

A processor also has limited support for handling multiple threads concurrently. At some point the OS or JVM will spend more time switching threads, than threads spend executing their code.

That is a good reason for the ScheduledThreadPoolExecutor to be designed the way it is. You can put any amount of jobs on the queue, but there are never executed more jobs at the same time than can be run efficiently. It's up to you to balance that, of course.

If your tasks are IO bound, I'd set the pool size small, and if they are CPU bound, a bit larger (32 or so). You can also make multiple ScheduledThreadPoolExecutors, one for IO bound tasks and one for CPU bound tasks.