I am trying to create a system where it has a number of queued slots and it accepts X incoming services. Now each service arrives/departs at different times so i could have one arrive 10 seconds from now and departs 20 seconds after arrival while the one after that could arrive sooner/later. Is the best way to implement this is to have 2 threads - one that is going through a loop to clear the queue while another thread is going through another loop generating new services? It is quite possible a new service is generated while another service is being serviced.:

Thread 1:

while(X>0) {  //has more incoming services
      masterTime++;
     if (currentServiceFinishTime > masterTime) {
     } else {
           removeCurrentService();
           startNextService();

    }    

}
   
thread 2:
 generateNextServiceArrivalTime() {
     while (X>0) {
           getNextService();
          if (queueHasRoom) {
                addNextService();
          } else if(arrivalTime +currentTime >currentServiceTime) {
               removeCurrentService(); 
               initiateNextServiceInQueue();
              updateMasterTime();
               addNextService();
        } else {
              rejectIncomingService(); //queue is full and the current service is not going to be done before the incoming service arrives
        }

}

is this way of doing it too confusing? any better way to implement this? thanks!

It sounds ok to use 2 threads to add and remove. Im guessing that the queue is in the form of an array with a FIFO (first in first out) policy. One idea may be if a thread access a method to add to the que, if that queue is full then call wait() (this will force the accessing thread to effectively pause and surrender it's key (if things are sychnronized)) then when another thread accesses the remove method that can include a call to notify() or notifyAll() (which will then wake the waiting thread) The idea being that as soon as something has been cleared, there is room in the queue for something else. The same can be applied for when the thread that is removing from the queue finds the queue is empty (in this case if empty then call wait() then when thread adds something then calls notifyAll(). Hopefully this would mean that things would get paused but would eventually get access and you would never have to discard any request. (careful with deadlock and shared resources)

Make it synchronized to avoid memory inconsistency errors

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.