soulmachine
soulmachine

Reputation: 4163

Why doesn't DelayQueue use PriorityBlockingQueue internally?

When I read the source code of DelayQueue, I think that DelayQueue is just a special case of PriorityBlockingQueue, thus DelayQueue can be simply implemented by wrapping a PriorityBlockingQueue internally.

So here comes my question, why doesn't DelayQueue use PriorityBlockingQueue internally ? What's the difference between DelayQueue and PriorityBlockingQueue?

Upvotes: 0

Views: 689

Answers (1)

Jacob G.
Jacob G.

Reputation: 29710

A DelayQueue is an implementation of a BlockingQueue where its elements must implement the Delayed interface, and can only be removed from the Queue after a specific amount of time has passed (the delay).

A PriorityBlockingQueue is an implementation of a BlockingQueue where an element's delay would play no part in its blocking mechanism. The elements in a PriorityBlockingQueue are prioritized depending on their natural ordering, or a Comparator passed to one of its constructors.

Both Queues will block when the user attempts to poll them when they are empty, meaning that the program will not continue until an element is offered to the Queue, most likely on a different thread.

You also must note that the elements of a DelayQueue are not prioritized via a Comparator, but rather via the use of locks and monitors.

A DelayQueue does use a backing PriorityQueue, but it still needs to write its own blocking mechanism, as that implementation differs from a PriorityBlockingQueue (which, when blocking, is notified of an offered element which it immediately returns to the caller).

Upvotes: 4

Related Questions