Monday, July 21, 2014

Thread Pool

Thread pool: a collection of threads, the size of which is bounded.
Java provides thread pools through the Executor framework.
[Thoughts]: The following class implements part of a simple HTTP server。 If you don't use parallel computing, it will have poor ferformance becasue process request might frequently blocks on I/O.
Executors: 

  • provide a layer of indirection between a client and the execution of a task; instead of client executing a task directly, an intermediate object executes the task; 
  • Allow you to manage the execution of asynchronous tasks without having to explicitly manage the lifecycle of threads. 
newFixedthreadPool:Saves time, because do not need to pay for thread creation overhead for every single task.
newCachedThreadPool: create as many threads as it needs during the execution of a program and then will stop creating new threads as it recycles the old ones.

class TaskExecutionWebServer throws IOException{
  private static final int nthreads = 100;// control the number of threads launched. 
  private static final int serverport = 8080;
  private static final Executor exec = executors.newFixedthreadPool(nthreads);

  public static void main(Strings[] arg){
    ServerSocket serversocket = new ServerSocket(serverport);
    while(true){
      final Socket connection = serversocket.accept();
      Runnable task = new Runnable(){
        public void run(){
        Worker.handleRequest(connection);
        }
      };
    exec.execute(task);
  }
 }
}

No comments:

Post a Comment