Wednesday 22 March 2017

What is Thread Pool in Java and why we need it?


Java Thread pool represents a group of worker threads that are waiting for the job and reuse many times. Thread pool creates Thread and manages them. Instead of creating Thread and discarding them once task is done, thread-pool reuses threads in form of worker thread.

In case of thread pool, a group of fixed size threads are created i.e. it also limits number of clients based upon how many thread per JVM is allowed, which is obviously a limited number. A thread from the thread pool is pulled out and assigned a job by the service provider. After completion of the job, thread is contained in the thread pool again.

Advantage of Java Thread Pool
Better performance, it saves time because there is no need to create new thread. The thread pool is one of essential facility any multi-threaded server side Java application requires. One example of using thread pool is creating a web server, which processes client request.

If only one thread is used to process client request, than it subsequently limit how many client can access server concurrently. In order to support large number of clients, you may decide to use one thread per request paradigm, in which each request is processed by separate Thread, but this require Thread to be created, when request arrived.  Since creation of Thread is time consuming process, it delays request processing.

Since Thread are usually created and pooled when application starts, your server can immediately start request processing, which can further improve server’s response time.

Real time usage
It is used in Servlet and JSP where container creates a thread pool to process the request.

Thread pools help us to better manage threads and decoupling task submission from execution. Thread pool and Executor framework introduced in Java 5 is an excellent thread pool provided by library.


No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...