Bounded PriorityBlockingQueue

后端 未结 9 1161
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 17:56

    If the order of the Runnables you want to execute is not strict (as is: it may occur that some lower priority tasks are executed even though higher priority tasks exist), then I would suggest the following, which boils down to periodically cutting the PriorityQueue down in size:

    if (queue.size() > MIN_RETAIN * 2){
        ArrayList toRetain = new ArrayList(MIN_RETAIN);
        queue.drainTo(toRetain, MIN_RETAIN);
        queue.clear();
        for (T t : toRetain){
          queue.offer(t);
        }
    }
    

    This will obviously fail if the order needs to be strict, as draining will lead to a moment, wenn low priority task will retrieved from the queue using concurrent access.

    The advantages are, that this is thread-safe and likely to get as fast as you can do with the priority queue design.

提交回复
热议问题