How do I search a queue for a specific object and then prioritise this object over the rest of the objects in the queue.

For example, I have a list of objects within the queue that each need to be processed, but I need to prioritise certain objects over others. At the moment it's a linked list so they're being executed in the order they are added to the queue, but say that an object was added that had priority, it needs to jump to the top of the queue to be executed before the rest.

private Queue<Packet> packetQueue = new LinkedList<Packet>();

@Override
public boolean handlePacketQueue() {
    try {
        Packet p = null;
        synchronized (packetQueue) {
                p = packetQueue.poll();
        }
        if (p == null) {
            return false;
        }
        packetType = p.getPacketId();
        packetSize = p.getPacketLength();
        buffer = p.getPacketData();
        if (packetType > 0) {
            PacketManager.handlePacket(this, packetType, packetSize);
        }
        p = null;
        return true;
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return false;
}

Now I need to prioritise a packet with a specific id, before executing any other. Can someone help me as to how I'd do this?

有帮助吗?

解决方案

When construct PriorityQueue, you specify a Comparator to determine the order.

In JDK8, with lambda, you can do it like this,

private PriorityQueue<Packet> packetQueue = new PriorityQueue<>((p1, p2) ->
    p1.getPacketId() == specified_id ? -1 : 0);

This gives specified_id a boost while others remains same. Implement your prioritization in the Comparator.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top