Thread per Request

17 Mar 2011 by

Thread per Request/Connection

Thread per Request/Connection

Thread per request or connection has been introduced in order to maximize the system resource and provide responsiveness to users which single thread is not capable. Thread per request or connection architecture will create a thread for each request from a client. In other words, server can create a number of threads as per request. The only limitation is software and hardware capacity. Thread per request is one among thread in distributed systems architecture. This architecture is coming with advantages and disadvantages.

Advantage

  • No waiting users
  • Maximize system resources
  • It is a little hard to develop unless you follow the guideline strictly

Disadvantage

  • A lot of overhead in creating and destroying threads for many requests or connections
  • Server might crash if the number of requests is beyond the server’s capacity

Thread per Request Algorithm

  1. Create a Server Socket
  2. Wait for and accept client’s request
  3. Create parallel line of execution to attend the requirement of the new client
    1. Receive the parameters of the communication established by the master (socket or input/output data streams)
    2. Attend client’s request (send and receive from socket, do something as needed)
    3. Disconnect when finish
  4. Go to step 2

Example

In this example we demonstrate the ability of server than can calculate fibonacci number for every client request without let them waiting for one another.

Structure of the code

Server

  • MultiThreadFibonacciServer.java (Main server)
  • FibonacciHandlerServer.java (Worker thread for creating parallel line of execution)

Client

  • MultiThreadFibonacciClient.java (Main client)
  • FibonacciHandlerClient.java (Worker thread for multiple connections to server)

MultiThreadFibonacciServer.java

import java.net.*;
/**
 *
 * @author http://lycog.com
 */
public class MultiThreadFibonacciServer {

  public static void main(String[] args) {
    try {
      //Step 1: Create Server Socket
      ServerSocket server = new ServerSocket(9999);
      int index = 0;

      while (true) {
        System.out.println("Multithread: Wait for client to connect....");
        //Step 2: Wait for client
        Socket socket = server.accept();

        //Step 3: Create parallel line of execution
        FibonacciHandlerServer fh = new FibonacciHandlerServer(socket, index);
        fh.start();
        index++;
      }
    } catch (Exception e) {
      System.out.println(e);
    }
  }
}

FibonacciHandlerServer.java

import java.io.PrintWriter;
import java.net.Socket;
/**
 *
 * @author http://lycog.com
 */
public class FibonacciHandlerServer extends Thread {

  private Socket socket = null;
  private int index = 0;

  //Step 3.1: Receive paramater from master
  public FibonacciHandlerServer(Socket socket, int index) {
    this.socket = socket;
    this.index = index;
  }

  @Override
  public void run() {
    //Step 3.2: Attend client's request
    try {
      System.out.println("----------------------------------------");
      System.out.println("Thread-" + index + " serves connection from "
              + socket.getInetAddress() + ":" + socket.getPort());
      PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

      System.out.println("Thread-" + index + " is calculating fibonaci");
      long f = fib(45);

      System.out.println("Thread-" + index + " is sending result");
      out.println("" + f);
      System.out.println("----------------------------------------");
    } catch (Exception e) {
      System.out.println(e);
    }
    //Step 3.3: Disconnect when finish
  }

  private long fib(long n) {
    if (n == 0) {
      return 0L;
    }

    if (n == 1) {
      return 1L;
    }

    return (fib(n - 1) + fib(n - 2));
  }
}

MultiThreadFibonacciClient.java

/**
 *
 * @author http://lycog.com
 */
public class MultiThreadFibonacciClient {
  public static void main(String[] args) {
    Thread[] t = new Thread[5];

    for (int i = 0; i < t.length; i++) {
      t[i] = new FibonacciHandlerClient("Thread-" + i);
      t[i].start();
      try {
        Thread.sleep(1000);
      } catch (InterruptedException ie) {
      }
    }
  }
}

FibonacciHandlerClient.java

import java.net.*;
import java.io.*;
/**
 *
 * @author http://lycog.com
 */
public class FibonacciHandlerClient extends Thread {

  private String name;

  public FibonacciHandlerClient() {
  }

  public FibonacciHandlerClient(String name) {
    this.name = name;
  }

  @Override
  public void run() {
    try {
      Socket socket = new Socket("127.0.0.1", 9999);

      System.out.println(name + " connect on port " + socket.getLocalPort());
      BufferedReader in = new BufferedReader(new InputStreamReader(
              socket.getInputStream()));

      String val = in.readLine();
      System.out.println("Fibonaci = " + val);
      socket.close();
    } catch (Exception e) {
      System.out.println(e);
    }
  }
}

 

No responses yet

Leave a Reply