Video in progress

Strong Middle 🧺 Collections

If you write your own Iterator or Iterable that reads pages from a DB, what traps can you fall into?

The most common mistakes: hasNext() having side effects (if it is called twice, an element is lost), next() returning null at the end instead of throwing NoSuchElementException, an Iterable that turns out to be one-shot, and an opened resource (cursor, connection) that never gets closed.

📖 Answer

class PagedIterator implements Iterator<Order> {
    private static final int PAGE = 500;
    private final OrderRepo repo;
    private List<Order> page = List.of();
    private int pos;
    private long lastId;
    private boolean done;

    PagedIterator(OrderRepo repo) { this.repo = repo; }

    @Override public boolean hasNext() {
        if (pos < page.size()) return true;
        if (done) return false;
        page = repo.findAfter(lastId, PAGE);   // keyset pagination: id > lastId
        pos = 0;
        done = page.size() < PAGE;
        if (!page.isEmpty()) lastId = page.getLast().id();
        return !page.isEmpty();
    }

    @Override public Order next() {
        if (!hasNext()) throw new NoSuchElementException();
        return page.get(pos++);
    }
}

Here hasNext() is idempotent: no matter how many times it is called, a new page is loaded only when the current one runs out.

The traps:

  • doing "read the next one ahead of time" inside hasNext() and advancing the state incorrectly. Someone calls hasNext() twice (in a debug log, say) and an element gets dropped.
  • Iterable.iterator() must return a new iterator on every call. If you return a single iterator, the second for-each quietly iterates over nothing.
  • remove() by default throws UnsupportedOperationException. That is normal, so don't implement it halfway.
  • Resources. If the caller doesn't iterate an iterator over a JDBC ResultSet to the end, the cursor stays open, and Iterator has no close. In that case a Stream + onClose (with try-with-resources) or a callback style is better.
  • Offset pagination (LIMIT/OFFSET) repeats or skips elements if new rows are inserted during iteration. That is why the example uses id > lastId.