1

I have a blocking priority queue which stores Objects of type Message, message has String[] data = new String[10]. Now I have to iterate over whole blocking Queue, check if its Object message's 2nd element is equal to 6th element of an incoming message.

The comparator of Messages is not based on 6th element which needs to be updated. Problem is that if I take out an object then how to put it at same position and if I use the code below to update it then anytime iter.next() is run it may start pointing to next Object.

Here is what I am trying.

public synchronized void updateAck(Message ackMessage)
    {
        Iterator iter  = localQ.iterator(); // localQ is the blocking priority queue here
        while(iter.hasNext())
        {
            if(((Message)iter.next()).data[2].equalsIgnoreCase(ackMessage.data[6]))
            {
                (Integer.parseInt((Message)iter.next()).data[6])+1);

            }
        }
    }
Yogesh
  • 1,307
  • 3
  • 13
  • 18

2 Answers2

1

Instead of directly using (Message)iter.next() in your if conditions, try this.

Message queMessage = (Message)iter.next();

Full code

 while(iter.hasNext())
{

    Message queMessage = (Message)iter.next(); //you will be invoking .next() only once

     if(queMessage.data[2].equalsIgnoreCase(ackMessage.data[6]))
     {
          (Integer.parseInt(queMessage.data[6])+1);

     }
}
kensen john
  • 5,439
  • 5
  • 28
  • 36
0

It seems like doing this operation on a live queue is somewhat dangerous, depending on what the downstream consumer is expecting.

How about this:

  • When an ack comes in, initialize a new BlockingQueue
  • Atomic swap in the new, empty queue for the old full one
  • Drain the elements from the old queue into the new one, making whatever comparisons/changes need to be made element by element

If this happens a lot, maybe you need a pair of queues; one is the live one; the other is the shadow.

andersoj
  • 22,406
  • 7
  • 62
  • 73