TheAlgorithms/Java · error · IllegalStateException

MinPriorityQueue is empty. Cannot peek.

Error message

MinPriorityQueue is empty. Cannot peek.

What it means

Thrown by MinPriorityQueue.peek() when isEmpty() returns true. The queue stores the minimum at heap[1] using 1-based array indexing, so peeking an empty queue would read an uninitialized slot. The guard enforces the non-empty precondition before reading the root.

Source

Thrown at src/main/java/com/thealgorithms/datastructures/heaps/MinPriorityQueue.java:69

            if (this.heap[k] < this.heap[k / 2]) {
                int temp = this.heap[k];
                this.heap[k] = this.heap[k / 2];
                this.heap[k / 2] = temp;
            }
            k = k / 2;
        }
        this.size++;
    }

    /**
     * Retrieves the highest priority value (the minimum) without removing it.
     *
     * @return the minimum value in the queue
     * @throws IllegalStateException if the queue is empty
     */
    public int peek() {
        if (isEmpty()) {
            throw new IllegalStateException("MinPriorityQueue is empty. Cannot peek.");
        }
        return this.heap[1];
    }

    /**
     * Checks whether the queue is empty.
     *
     * @return true if the queue is empty, false otherwise
     */
    public boolean isEmpty() {
        return size == 0;
    }

    /**
     * Checks whether the queue is full.
     *
     * @return true if the queue is full, false otherwise
     */

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Guard with isEmpty(): `return pq.isEmpty() ? OptionalInt.empty() : OptionalInt.of(pq.peek());`.
  2. Ensure at least one insert precedes any peek.
  3. Catch IllegalStateException and return a sentinel/empty result.
  4. Structure the consumer to only run after the producer signals population.

Example fix

// before
int min = pq.peek();

// after
if (pq.isEmpty()) {
    return OptionalInt.empty();
}
return OptionalInt.of(pq.peek());
Defensive patterns

Strategy: validation

Validate before calling

if (!pq.isEmpty()) {
    return pq.peek();
}
return OptionalInt.empty();

Try / catch

try {
    return OptionalInt.of(pq.peek());
} catch (IllegalStateException e) {
    return OptionalInt.empty();
}

Prevention

When it happens

Trigger: Calling peek on a freshly constructed queue with no inserts. Calling peek after draining all elements via delete.

Common situations: Polling a queue that may not yet be populated by a producer. Top-of-loop read before the first insert. Empty-input edge case in a merge or scheduling algorithm.

Related errors


AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13). Data as JSON: /api/errors/cbc189c413b460fe. Report an issue: GitHub.