Thread Pool

18 Mar 2011 by

Thread Pool

Thread Pool

In previous post you may understand the architecture of single thread and thread per request in distributed systems. Here we will see another architecture called Thread Pool. Thread pool pre-defines a number of thread running in its pool. Let’s say we have 2 threads in the pool, then the server is capable of running only 2 requests at the same time. Other requests must wait in queue until the 2 threads in the pool finish their work. In real world applications, we see a lot of servers fall into this category. For example, Apache web server, IIS server, etc. The advantages and disadvantages are discussed below:


  • By optimal number of thread in the pool, the chance of server crash is highly reduced
  • Has little request in queue


  • Must do performance tuning for specific hardware capacity
  • Difficult to develop until you take advantage of Java concurrency package

Thread Pool in Java

From Java SE 1.5, there is a concurrency package that make implementation of thread pool be ever easier.

  • Import necessary class
    • import java.util.concurrent.ExecutorService;
    • import java.util.concurrent.Executors;
  • Create pool and define pool size
    • ExecutorService pool = null;
    • pool = Executors.newFixedThreadPool(POOL_SIZE);
  • Execute thread in the pool
    • FibonacciHandlerServer fh = new FibonacciHandlerServer(socket, index);
    • pool.execute(fh);


In example below, I will show you to create Fibonacci thread pool. The structure of the file is as following:



import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
 * @author
public class ThreadPoolFibonacci {

  public static void main(String[] args) {
    ServerSocket server = null;
    ExecutorService pool = null;
    int poolSize = 3;
    int index = 0;
    try {
      //Create server socket
      server = new ServerSocket(9999);

      //Create pool and define pool size
      pool = Executors.newFixedThreadPool(poolSize);
      while (true) {
        System.out.println("Thread Pool is waiting for client....");
        //Wait for client to connect
        Socket socket = server.accept();

        //Declare thread associated with a request
        FibonacciHandlerServer fh = new FibonacciHandlerServer(socket, index);
        //Execute thread in the pool

    } catch (Exception e) {


No responses yet

Leave a Reply

Time limit is exhausted. Please reload the CAPTCHA.