Priority Queue for handling messages on queue which requires timebound release

Viewed 62

I am implementing a solution that will delay messages with variable time intervals and release them as they expire.

So, a message arrives and it is supposed to be delayed by 5 seconds, then I will put them in 5-second delay. Whereas, if a message arrives with a 15s delay, I will put them in 15 seconds bucket.

I am thinking of using a PriorityQueue.

Implementation looks like:

PriorityQueue<ReleaseCondition> queue = new PriorityQueue<>(1000, new TimeComparator());

Declare 
Class TimeComparator implements Comparator<MessageRelease> {
    public int compare(MessageRelease m1, MessageRelease m2) {
        if (m1.timestamp < m2.timestamp) {
            return 1;
        } else if (m1.timestamp > m2.timestamp) {
            return -1;
        }
        return 0;
    }
}

To me I see this working when I used random delays, I see the oldest message in front. Idea for me will be to read all messages from front and remove them as they meet expiration policy.

Want to check if this is fool proof approach. I am writing tests, but thinking if I should have used something which is more off the shelf product.

1 Answers

This topic has been discussed in this discussion as well. Time-based thread-safe priority queue

Your approach is one of the two methods defined in the discussion. Priority Queues will allow you to always place the message which will expire first in front of the queue. And since it is always ordered, it will meet the purpose you have described.

Good implementation code as well.

Related