Biblioteca Java - Rev 3

Subversion Repositories:
Rev:
/*
 * NetworkService.java
 */

package lab.scd.fire.tpool2;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Class created by @author Mihai HULEA at Feb 22, 2005.
 *
 * This class is part of the labs project.
 *
 * Ecesta este un exemplu preluat din documentatia sdk 1.5.0 care exemplifica modul
 * de folosire a unui threadpool pentru crearea unui server ce deserveste clienti pe
 * un numar limitat de fire.
 *
 */

class NetworkService {
    private final ServerSocket serverSocket;
    private final ExecutorService pool;

    public NetworkService(int port, int poolSize) throws IOException {
      serverSocket = new ServerSocket(port);
      pool = Executors.newFixedThreadPool(poolSize);
    }
 
    public void serve() {
      try {
        for (;;) {
          pool.execute(new Handler(serverSocket.accept()));
        }
      } catch (IOException ex) {
        pool.shutdown();
      }
    }
  }

/**
 * Clasa implementeaza protocolul de comunicatie cu clientul. Pentru fiecare client
 * va fi lansat in executie un fir de tip Handler.
 */

  class Handler implements Runnable {
    private final Socket socket;
    Handler(Socket socket) { this.socket = socket; }
    public void run() {
      // read and service request
    }
 }