1

I'm wondering how multiple thread pools compete for CPU resources in Java? I have multiple thread pools for different tasks. If my CPU has N core and I assign each thread pool with N maximum threads.

  • If all the thread pools start their task at the same time, does that means they will compete the CPU resources together?
  • How do they compete with each other? Does each thread hold the CPU resource for a period of time? Or does each thread pool hold the CPU resource for a period of time?

The benefit of having different thread pools for different tasks is that the service won't get starved. In the meanwhile, does that mean more thread pools cause more context switching and make the program slower?

In general, is having multiple thread pools a better design than a single thread pool?

LittleW
  • 11
  • 1

1 Answers1

0

Each thread pool contains a group of worker threads that try to get tasks from task queue and execute them, and operating system will schedule all threads. There is no such thing as each thread pool holding the CPU resource for a period of time.

If task queue of a thread pool is empty, then all keep-alive(corePoolSize) worker threads in this thread pool will be blocked on workQueue.take() method and wait for new tasks(thread enters WAITING state).

Different thread pool are suitable for different types of tasks. For example, Executors#newCachedThreadPool is suitable for many short-lived asynchronous tasks. You should customize different thread pools for different types of tasks.

zysaaa
  • 1,777
  • 2
  • 8
  • 19