Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does ScheduledThreadPoolExecutor only accept a fixed number of threads?

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 ?

like image 379
Matthew Avatar asked Jul 28 '10 12:07

Matthew


People also ask

How many threads executor can create?

Executors Framework While it is easy to create one or two threads and run them, it becomes a problem when your application requires creating 20 or 30 threads for running tasks concurrently.

What is ScheduledThreadPoolExecutor?

ScheduledThreadPoolExecutor is a subclass of ThreadPoolExecutor and can additionally schedule commands to run after a given delay, or to execute periodically.


1 Answers

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.

like image 64
extraneon Avatar answered Oct 14 '22 12:10

extraneon