Universität Paderborn - Home Universität Paderborn
Die Universität der Informationsgesellschaft

Parallel Programming WS 2014/2015 - File LicenseServer.java

public class LicenseServer extends Thread {
   private Channel reqservChan;
   private Channel relservChan;
   public static final int N = 4;
   public static final int REQUEST = 1;
   public static final int RELEASE = 2;
   private int avail = N; // number of available licenses
   private Queue pending;
   private boolean running = true;

   public LicenseServer(Channel reqc, Channel relc) {
      reqservChan = reqc;
      relservChan = relc;
      pending = new Queue();
   }

   public void stopIt() {
      running = false;
   }

   public void run() {
      System.out.println("Server started");
      Message msg;
      while (running || !pending.empty() || avail < N) {
            if (!reqservChan.empty()) {
               msg = (Message) reqservChan.receive();

               System.out.printf("REQ from %s (%d licenses available)\n",
                                 msg.getId(), avail);
               if (avail > 0) {
                  avail--;
                  // send request reply on client channel:
                  msg.getChan().send(null);
               } else {
                  pending.enqueue(msg);
                  System.out.printf("REQ from %s put in queue\n",
                                 msg.getId());
               }
            }

            if (!relservChan.empty()) {
               msg = (Message) relservChan.receive();

               System.out.printf("REL from %s\n",
                                 msg.getId());
               // send release reply on client channel:
               msg.getChan().send(null);
               if (pending.empty()) {
                  avail++;
               } else {
                  msg = (Message) pending.front();
                  pending.dequeue();
                  System.out.printf("REQ from %s taken from queue\n",
                                 msg.getId());
                  // send request reply on client channel:
                  msg.getChan().send(null);
               }
            }
      }
      System.out.printf("Server terminates\n");
   }
}

Generiert mit Camelot | Probleme mit Camelot? | Geändert am: 26.01.2015