Search code examples
javablockingqueue

Consuming from more than one BlockingQueue


I am trying to implement Elevator system which contains Elevator class that takes requests from ElevatorController and moves accordingly. ElevatorController maintains 2 blocking queues, one for upward requests and other for downward requests.

I want the elevator to look at both the queues and serve if any request appears in one of the queues.

If i use upwardQueue.take(), the elevator will wait for some request to appear it the upwardQueue. But at the same time, if a request appears in downwardQueue how can the elevator consume it?

Basically, how can the elevator consume requests from both the queues?


Solution

  • The ideal solution is to create a class specifically for requests.

    public class FloorRequest {
    
      private final int floor;
      private final Direction direction;
    
      public FloorRequest(int floor, Direction direction) {
        this.floor = floor;
        this.direction = direction;
      }  
    
      public int getFloor() { return floor; }
      public Direction getDirection() { return direction; }
    
      public enum Direction {
        UP, DOWN
      }
    
    }
    

    Then you would use a single BlockingQueue of FloorRequest elements.

    BlockingQueue<FloorRequest> queue = ...;
    while (/* some condition */) {
      FloorRequest request = queue.take();
      switch (request.getDirection()) {
        case UP:
          // do something
          break;
        case DOWN:
          // do something else
          break;
      }
    }