Java Reference
In-Depth Information
C.1.1. Implementing the Results interface with the
ForkingStreamConsumer
The getResults method can be implemented as follows:
public Results getResults() {
ForkingStreamConsumer<T> consumer = build();
try {
stream.sequential().forEach(consumer);
} finally {
consumer.finish();
}
return consumer;
}
The ForkingStreamConsumer implements both the Results interface defined previously and the
Consumer interface. As you'll see when we analyze its implementation in more detail, its main
task is to consume all the elements in the stream and multiplex them to a number of
BlockingQueues equal to the number of operations submitted via the fork method. Note that it is
ensured that the stream is sequential, because if the method forEach were performed on a
parallel stream, its elements could be pushed to the queues out of order. The finish method adds
special elements to those queues to signal that there are no more items to be processed. The
build method used to create the ForkingStreamConsumer is shown in the next listing.
Listing C.2. The build method used to create ForkingStreamConsumer
 
Search WWH ::




Custom Search