Java Reference
In-Depth Information
So far, so good, but we said that one of the main reasons for implementing the WordCounter in
functional terms was to be able to easily parallelize this operation, so let's see how this works.
Making the WordCounter work in parallel
You could try to speed up the word-counting operation using a parallel stream, as follows:
System.out.println("Found " + countWords(stream.parallel()) + " words");
Unfortunately, this time the output is
Found 25 words
Evidently something has gone wrong, but what? The problem isn't hard to discover. Because the
original String is split at arbitrary positions, sometimes a word is divided in two and then
counted twice. In general, this demonstrates that going from a sequential stream to a parallel
one can lead to a wrong result if this result may be affected by the position where the stream is
split.
How can you fix this issue? The solution consists of ensuring that the String isn't split at a
random position but only at the end of a word. To do this, you'll have to implement a Spliterator
of Character that splits a String only between two words, as shown in the following listing, and
then creates the parallel stream from it.
Listing 7.6. The WordCounterSpliterator
 
Search WWH ::




Custom Search