Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Java LinkedList spliterator: traversal binds after creation

Last updated: 5 Oct 20264 min read
tutorial
IntermediateBy AITrove Editorial

LinkedList.spliterator is late-binding, so a change before its first traversal or size query can become part of the traversal.

Place the binding boundary

Creating a spliterator is not necessarily a snapshot. In this fixture, a receipt added before traversal appears in the output. After a size query binds a second spliterator, a structural edit invalidates its expected state and the tested JDK reports ConcurrentModificationException.

The fail-fast exception is best-effort, not a synchronization protocol. Synchronized iteration covers ownership of a scan; Spliterator characteristics explains which traversal properties may be advertised.

Choose snapshot semantics explicitly

If a parallel computation must process one stable version, copy the list under the appropriate lock before traversing. A late-binding spliterator only narrows the timing window; it does not make concurrent writers safe or define an immutable view.

Working program

Java
import java.util.*;

public class ReceiptSpliteratorBoundary {
    public static void main(String[] args) {
        LinkedList<String> receipts = new LinkedList<String>();
        receipts.add("R-17");
        Spliterator<String> pending = receipts.spliterator();
        receipts.add("R-47");
        pending.forEachRemaining(System.out::println);

        Spliterator<String> bound = receipts.spliterator();
        bound.estimateSize();
        receipts.add("R-82");
        try { bound.forEachRemaining(receipt -> { }); }
        catch (ConcurrentModificationException changed) { System.out.println("bound scan invalidated"); }
    }
}

Output

Output
R-17
R-47
bound scan invalidated

Cost and ownership

A full traversal visits O(n) elements. Splitting may buffer elements and consume additional memory; a plain sequential pass does not turn the list into a snapshot. The performance and failure boundary depend on when binding occurs.

Common Mistakes

  • Do not assume spliterator creation copies the list.
  • Do not use a fail-fast exception as a concurrency guarantee.
  • Do not mutate the backing list during a supposedly stable scan.

Read next

Java Spliterator: split traversal without inventing characteristics, Java LinkedList fail-fast iterators: a bug signal, not safety, Java synchronized LinkedList iteration: hold the wrapper lock for the whole scan, Java LinkedList: operations, internals and failure cases.

java
collections
linkedlist-spliterator-binding
Storage details