user1950349
user1950349

Reputation: 5146

setup ordering in priority blocking queue

I have a PriorityBlockingQueue in which I am adding SocketHolder as shown below. And let's say current datacenter where this code is running is abc. We have three datacenters abc, def and pqr.

private static final PriorityBlockingQueue<SocketHolder> liveQueue = new PriorityBlockingQueue<>();

for (SocketHolder socket : listOfSockets) {
    liveQueue.add(socket);
}

Now what I need to do is:

Below is my SocketHolder class that implements Comparable interface but I am confuse what I need to do in my compareTo method so that at the top of liveQueue (after adding elements to it) we have all SocketHolder whose datacenter are current datacenter and then followed by other datacenter in which I have no priority.

public final class SocketHolder implements Comparable<SocketHolder> {
  private final Socket socket;
  private final Datacenter dc;
  private final Context context;

  public SocketHolder(Socket socket, Datacenter dc, Context context) {
    super();
    this.socket = socket;
    this.dc = dc;
    this.context = context;
  }

  @Override
  public int compareTo(SocketHolder o) {
    // String currentDC = Utils.CURRENT_DATACENTER.get().name();
    return 0;
  }
}

Upvotes: 1

Views: 293

Answers (1)

Ian Mc
Ian Mc

Reputation: 5829

The live datacenter will be assigned priority 1, and the other datacenters priority 2. The queue will process the lowest priority first.

public final class SocketHolder implements Comparable<SocketHolder> {
   private final Socket socket;
   private final Datacenter dc;
   private final Context context;
   private final int priority;

   public SocketHolder(Socket socket, Datacenter dc, Context context) {
      super();
      this.socket = socket;
      this.dc = dc;
      this.context = context;
      this.priority = this.dc.getName().equals(Utils.CURRENT_DATACENTER.get().name()) ? 1 : 2;
   }

   @Override
   public int compareTo(SocketHolder o) {
       return Integer.compare(this.priority, o.priority);
   }
}

Upvotes: 1

Related Questions