Java Reference
In-Depth Information
This Spliterator is created from the String to be parsed and iterates over its Characters by
holding the index of the one currently being traversed. Let's quickly revisit the methods of the
WordCounterSpliterator implementing the Spliterator interface:
The
tryAdvance
method feeds the
Consumer
with the
Character
in the
String
at the current index
position and increments this position. The
Consumer
passed as argument is an internal Java class
forwarding the consumed
Character
to the set of functions that have to be applied to it while
traversing the stream, which in this case is only a reducing function, namely, the
accumulate
method
of the
WordCounter
class. The
tryAdvance
method returns
true
if the new cursor position is less
than the total
String
length and there are further
Character
s to be iterated.
The
trySplit
method is the most important one in a
Spliterator
because it's the one defining the
logic used to split the data structure to be iterated. As you did in the
compute
method of the
RecursiveTask
implemented in
listing 7.1
(on how to use the fork/join framework), the first thing
you have to do here is set a limit under which you don't want to perform further splits. Here, you use a
very low limit of 10
Character
s only to make sure that your program will perform some splits with
the relatively short
String
you're parsing, but in real-world applications you'll have to use a higher
limit, as you did in the fork/join example, to avoid creating too many tasks. If the number of
remaining
Character
s to be traversed is under this limit, you return
null
to signal that no further
split is necessary. Conversely, if you need to perform a split, you set the candidate split position to the
half of the
String
chunk remaining to be parsed. But you don't use this split position directly because
Search WWH ::
Custom Search