Bounded PriorityBlockingQueue

后端 未结 9 1127
Happy的楠姐
Happy的楠姐 2021-01-01 17:47

PriorityBlockingQueue is unbounded, but I need to bound it somehow. What is the best way to achieve that?

For information, the bounded PriorityBlo

相关标签:
9条回答
  • 2021-01-01 18:11

    Not a single answer so far has all of the following properties:

    • Implements the BlockingQueue interface.
    • Supports removal of the absolute largest value.
    • No race conditions.

    Unfortunately, there is no BlockingQueue implementation in the standard Java library. You will either need to find an implementation or implement something yourself. Implementing a BlockingQueue will require some knowledge on proper locking.

    Here's what I suggest: Have a look at https://gist.github.com/JensRantil/30f812dd237039257a3d and use it as a template to implement your own wrapper around a SortedSet. Basically, all the locking is there and there are multiple unit tests (that will need some tweaking).

    0 讨论(0)
  • 2021-01-01 18:12

    There is another implementation here

    It seems to do what you are asking for:

    A BoundedPriorityQueue implements a priority queue with an upper bound on the number of elements. If the queue is not full, added elements are always added. If the queue is full and the added element is greater than the smallest element in the queue, the smallest element is removed and the new element is added. If the queue is full and the added element is not greater than the smallest element in the queue, the new element is not added.

    0 讨论(0)
  • 2021-01-01 18:22

    Have a look at the ForwardingQueue from the Google Collections API. For blocking semantics you could use a Semaphore.

    0 讨论(0)
提交回复
热议问题