Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#FFCCCC
class Helper {
  public void handle(Socket socket) {
    //... 		
  }	
}

final class RequestHandler {
  private final Helper helper = new Helper();
  private final ServerSocket server;

  private RequestHandler(int port) throws IOException {
    server = new ServerSocket(port);
  }
  
  public static RequestHandler newInstance(int port) throws IOException {
    return new RequestHandler(port0); // Selects next available port
  }
  
  public void handleRequest() {
    new Thread(new Runnable() {
      public void run() {
        try {
          helper.handle(server.accept());
	} catch (IOException e) {
 	  // Forward to handler   
        }
      }
    }).start();
  }
  // Other methods such as for shutting down the thread pool and task cancellation ...
}

...

Code Block
bgColor#ccccff
// class Helper remains unchanged

final class RequestHandler {
  private final Helper helper = new Helper();
  private final ServerSocket server;
  private final ExecutorService exec;
	 
  private RequestHandler(int port, int poolSize) throws IOException {
    server = new ServerSocket(port);
    exec = Executors.newFixedThreadPool(poolSize);
  }
	  
  public static RequestHandler newInstance(int port, int poolSize) throws IOException {
    return new RequestHandler(port0, poolSize); 
  }
	  
  public void handleRequest() {	
    Future<?> future   
    = exec.submit(new Runnable() {
      @Override public void run() {
	try {
  	  helper.handle(server.accept());
	} catch (IOException e) {
          // Forward to handler						
        }
      }
    });
  }
}

Wiki Markup
According to the Java API documentation for the {{Executor}} interface \[[API 06|AA. Java References#API 06]\] documentation for the {{Executor}} interface:

Wiki Markup
\[The Interface {{Executor}} is\] An object that executes submitted {{Runnable}} tasks. This interface provides a way of decoupling task submission from the mechanics of how each task will be run, including details of thread use, scheduling, etc. An {{Executor}} is normally used instead of explicitly creating threads.

...