0
\$\begingroup\$

I have a PriorityBlockingQueue in which I am adding SocketHolder. 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:

  • I have to setup some sort of ordering on liveQueue so that all SocketHolder whose datacenter is abc (which is current datacenter where the code is running), they should be at the top so which means when we retrieve it from this liveQueue all SocketHolder with abc datacenter should come out first and then later on all other SocketHolder with other dc's. Similarly for cases where current datacenter is either pqr or def.

This is my SocketHolder class that implements Comparable interface and 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.

Here is how I did: 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.name().equalsIgnoreCase(Utils.CURRENT_DATACENTER.get().name()) ? 1 : 2;
   }

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

I wanted to see if this is the right way to do it or is there is any better way.

\$\endgroup\$
1
\$\begingroup\$

You currently couple your SocketHolder class with the environment it exists in, as you have the comparable interface implemented in SocketHolder which in turn uses Utils.CURRENT_DATACENTER.get().name(). I don't think that this is a good idea, as this dependency seems unnecessary and makes isolated testing difficult. (Or in other words: bad gut-feeling ;-))

Suggestion: as you set up your priority queue in a specific environment, and at that place it is probably OK to know the environment. So, use the constructor for priority queue where you pass a Comparator explicitly, and write a comparator which basically does the same as the compareTo-method you have in your SocketHolder right now.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.