3

I am wondering why the default size of a PriorityQueue in Java is 11. I looked up the implementation and it made things more confusingly for me.

The priority queue is implemented as a heap. Its capacity is adjusted using this function:

/**
 * Increases the capacity of the array.
 *
 * @param minCapacity the desired minimum capacity
 */
private void grow(int minCapacity) {
    if (minCapacity < 0) // overflow
        throw new OutOfMemoryError();
    int oldCapacity = queue.length;
    // Double size if small; else grow by 50%
    int newCapacity = ((oldCapacity < 64)?
                       ((oldCapacity + 1) * 2):
                       ((oldCapacity / 2) * 3));
    if (newCapacity < 0) // overflow
        newCapacity = Integer.MAX_VALUE;
    if (newCapacity < minCapacity)
        newCapacity = minCapacity;
    queue = Arrays.copyOf(queue, newCapacity);
}

I don't understand the initial value 11 for the capacity. I think that the capacity should always be 2 to the number of levels. Any clarification?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Dimitris Leventeas
  • 1,622
  • 2
  • 16
  • 29
  • 11 is probably the smallest size at which a priority queue has any advantage over a sequential data structure. – user207421 Jun 02 '12 at 10:07

1 Answers1

3

11 is probably a number that was chosen more or less arbitrarily, as a trade off between memory consumption (a too large number would consume too much memory for nothing), and CPU consumption (a too low number would need too many resizes of the queue). And they probably benchmarked typical use cases to choose this number and the strategy used to resize the queue.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • If the size of heap is 11, then we need 4 consequent insertion/deletions to change the number of levels in the heap. Therefore, 11 is the best option in this regard between [8, 15]. Nevertheless, this line of thought does not scale for other values. – Dimitris Leventeas Jun 02 '12 at 10:47