Fork-join using spliterator and parallel streams.
Reference: https://java-8-tips.readthedocs.io/en/stable/parallelization.html
For more info about spliterators please refer my other github project:
Note that this project is the exact copy of my other github project: https://github.com/mtumilowicz/fork-join-find-minimum but using spliterator + parallel streams instead of fork-join API.
Find minimum in the stream of ints in a parallel way with full control over splitting.
- We have
int[] arr
, so we will be usingSpliterator.OfInt
(it removes overhead of autoboxing). - We implement
Spliterator.OfInt
inFindMinimumSpliterator
in the same way like fork-join, but note that:- splitting tear away part of
this
(sothis
spliterator has to be mutable) trySplit()
returns- a Spliterator covering some portion of the elements
- or null if this spliterator cannot be split
- splitting tear away part of
- Used characteristics:
IMMUTABLE
- Characteristic value signifying that the element source cannot be structurally modified; that is, elements cannot be added, replaced, or removed, so such changes cannot occur during traversal.NONNULL
- Characteristic value signifying that the source guarantees that encountered elements will not be null.ORDERED
- Characteristic value signifying that an encounter order is defined for elements.SIZED
- Characteristic value signifying that the value returned fromestimateSize()
prior to traversal or splitting represents a finite size that, in the absence of structural source modification, represents an exact count of the number of elements that would be encountered by a complete traversal.SUBSIZED
- Characteristic value signifying that all Spliterators resulting from trySplit() will be bothSIZED
andSUBSIZED
(This means that all child Spliterators, whether direct or indirect, willSIZED
).
- Constructing parallel
IntStream
fromSpliterator.OfInt
:IntStream intStream = StreamSupport.intStream(new FindMinimumSpliterator(array, 0, array.length - 1), true);
- On the
IntStream
we found minimum callingmin()
methodOptionalInt minimum = intStream.min();
Tested in FindMinimumTest
over array of 100_000
random elements.