Search code examples
javamultithreadingthreadpoolblockingqueue

Why does thread pool takes tasks independenty and not concurrently?


I am trying to get the basics very strong about thread pool. I learnt that it internally uses blocking queue to 'steal' tasks and run them into given threads in pool. Meaning that if I had 10 tasks and 5 threads, it could run only 5 tasks at the same time, until 1 finishes ENTIRELY.

Question is: Why not concurrently? Why not just time-slice those 10 tasks? What is the reason of this implementation?


Solution

  • Why not concurrently? Why not just time-slice those 10 tasks?

    You can have a thread pool that is able to perform ten concurrent tasks. You just need to configure it to have at least ten worker threads. "Time-slicing" tasks is what threads do. What thread pools do is:

    • Allow your program to control the number of threads that it uses to perform "background" tasks, and
    • Allow your program to re-use threads, which can be much more efficient than creating a new thread for each new task, and then destroying the thread when the task is complete.