Video in progress

Strong Middle 🧺 Collections

What is a Spliterator, and what should a collection you write yourself look like for parallel streams to work well on it?

A Spliterator is the source of a stream: it hands out elements and splits the work into chunks with trySplit(). The speed of a parallel stream depends on how even and cheap the splitting is, and on characteristics such as SIZED and ORDERED.

📖 Answer

Every Collection.stream() is actually built from spliterator(). In a sequential stream only tryAdvance/forEachRemaining are used. In a parallel one, ForkJoin tasks call trySplit() over and over and spread the chunks across threads.

Sources differ a lot:

  • ArrayList, arrays, IntStream.range: split evenly in half by index, SIZED | SUBSIZED. The best case for parallel.
  • HashMap/HashSet: split by table, the chunks are roughly equal, but the exact size is unknown.
  • LinkedList, Stream.iterate, BufferedReader.lines(): split poorly; they copy elements into an array and hand them out in batches. Little gain from parallel.

For your own structure, the easiest way is a ready-made helper:

@Override
public Spliterator<E> spliterator() {
    // over the internal array: splits properly, SIZED is added automatically
    return Spliterators.spliterator(elements, 0, size,
            Spliterator.ORDERED | Spliterator.IMMUTABLE);
}

If you only implement Iterable, the default spliterator() is built from the iterator: the size is unknown and the splitting is crude. parallelStream() on such a collection often turns out slower than the sequential one.

The characteristics also affect optimization: with SIZED, toArray allocates an array of the right size once; with DISTINCT, distinct() is almost free; with SORTED in natural order, sorted() is skipped. Declaring a wrong characteristic gives wrong results, for example putting DISTINCT on a source that actually has duplicates.