How and when to use Thread pool

What is Thread pool

A Thread pool is a set of worker threads created simultaneously, and each thread in this pool gets assigned with a task. Once a thread completes executing the assigned task, the thread goes back and waits in the pool, waiting for next task to be assigned.
Note that the thread does not die, after completion of its task, rather it goes and waits in the pool, for next Task to be assigned with.

Advantages of Thread pool

Limit the maximum number of threads to accomplish a task or set of tasks.
A thread is not started and ended, for every Task. With thread pool, we are avoid, starting and ending of threads multiple times.

Comparison with real life scenario:When ever you may need a paper notebook, you may goto market to purchase one at a time. Other solution would be to get a bunch of them and keep it with you, and use new one when old one is completed.

Situations when Thread pool, can be used

Lets consider a server program, which can process multiple requests simultaneously. A thread pool with a set of worker threads is started, each request is assigned to a thread. After the request is served, and has provided response to client, worker thread goes back and waits in thread pool.With this a worker thread is not started and ended, for each and every request, and hence responding to client requests is faster.

Another example, where we can use thread pools. Consider program to upload huge file. Using a single thread consumes more time, to upload complete file, and this is not recommended solution. Other approach would be to start few threads, each takes care of uploading a part of file. When each thread completes uploading its part, the thread dies. But consider, using thread pool, for this problem. Hence thread pool can provide ideal solution to such problems.

Please check back, for a ThreadPool example