Java Programming by Fain Yakov

Java Programming by Fain Yakov

Author:Fain, Yakov [Fain, Yakov]
Language: eng
Format: mobi, epub
ISBN: 9781118951576
Publisher: Wiley
Published: 2015-06-04T07:00:00+00:00


Parallel Versus Sequential Processing

A party of ten walk into an Octoberfest tent. They are seated at a table, and the waiter stops by. One of the guys say, “Please bring us ten mugs of Leffe Blonde, and do it as follows: go to the bar, fill the first mug and bring it here; then return and do the same with the second one. Repeat ten times.” The waiter politely replies, “Please don’t tell me how to bring your beer.” He went to the bar that had ten beer dispensers, filled all ten in parallel, and brought them all at the same time. The waiter optimized the process. He just needed the customers to tell him what to do but not how to do it.

Parallel processing rules! I’ve already mentioned this while describing iterating collections with the forEach() method in Lesson 13. The same applies to streams. When you invoke the method stream() on a data source, there is a chance that the data processing will be optimized and performed in parallel; the Java runtime may internally split the data into chunks, perform the operations in parallel, and reconstruct the result.

If you want to make sure that the processing is performed in parallel, use the method parallelStream() on your data, which may internally create multiple threads for processing the stream’s data. Java 7 introduced the Fork/Join framework for implementing parallelism, but it was not simple to code. In Java 8 the Fork/Join routine is hidden from application developers inside the stream implementation.

However, there is no guarantee that your application code will perform faster with parallelStream(). You need to benchmark your code by comparing the speed of parallelStream() versus the speed of stream(). The results depends on your application code as well as on the Java internals for your data source. Even the Java documentation states that parallelStream() returns a possibly parallel stream.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.