package com.tivoli.jmx.tutorial.server;

import java.util.TreeSet;
import java.util.SortedSet;

public class Httpd {

  public static void main(java.lang.String[] args) {
    SortedSet requestQueue = new TreeSet();
    Listener listener = new Listener(requestQueue);
    Httpd.logfile = new LogFile("Httpd.log");

    try {
      Httpd.logfile.open();
    } catch (IOException x) {
      System.err.println("Can't open logfile: " + x);
    }
    listener.start();

    HandlerPool handlers = new HandlerPool();

    while (listener.isListening()) {
      Request r = null;
      synchronized (requestQueue) {
        while (requestQueue.isEmpty()) {
          try { requestQueue.wait(); } catch (InterruptedException x) {}
        }
        r = (Request) requestQueue.first();
        requestQueue.remove(r);
      }

      Handler h = null;
      synchronized (handlers) {
        while ((h = handlers.reserve()) == null) {
          try { handlers.wait(); } catch (InterruptedException x) {}
        }
      }
      h.activate(r);
    }
  }
}