javaspliterator

Spliterator Java 8 - custom implementation


I am learning this Java 8 feature and I am really finding it difficult to understand the Spliterator interface's trySplit() method implementation in case of custom classes for parallel processing of the generated Stream.

Can anyone please help me with some good tutorial with a clear example?


Solution

  • An ideal trySplit method efficiently (without traversal) divides its elements exactly in half, allowing balanced parallel computation. Many departures from this ideal remain highly effective; for example, only approximately splitting an approximately balanced tree, or for a tree in which leaf nodes may contain either one or two elements, failing to further split these nodes. However, large deviations in balance and/or overly inefficient trySplit mechanics typically result in poor parallel performance.

    and the method structure with comments

     public Spliterator<T> trySplit() {
       int lo = origin; // divide range in half
       int mid = ((lo + fence) >>> 1) & ~1; // force midpoint to be even
       if (lo < mid) { // split out left half
         origin = mid; // reset this Spliterator's origin
         return new TaggedArraySpliterator<>(array, lo, mid);
       }
       else       // too small to split
         return null;
     }
    

    for more exposure read up on https://docs.oracle.com/javase/8/docs/api/java/util/Spliterator.html