Java Reference
In-Depth Information
coordinated [ 6 ] properly. This model is harder to think about [ 7 ] than a step-by-step sequential
model. For example, figure 1.5 shows a possible problem with two Threads trying to add a
number to a shared variable sum if they're not synchronized properly.
6 Traditionally via the keyword synchronized, but many subtle bugs arise from its misplacement.
Java 8's Stream-based parallelism encourages a functional programming style where
synchronized is rarely used; it focuses on partitioning the data rather than coordinating access
to it.
7 Aha—a source of pressure for the language to evolve!
Figure 1.5. A possible problem with two threads trying to add to a
shared sum variable. The result is 105 instead of an expected result of
108.
Java 8 also addresses both problems (boilerplate and obscurity involving processing collections
and difficulty leveraging multicore) with the Streams API (java.util .stream). The first design
motivator is that there are many data processing patterns (similar to filterApples in the previous
section, or operations familiar from database query languages such as SQL) that occur over and
over again and that would benefit from forming part of a library: filtering data based on a
criterion (for example, heavy apples), extracting data (for example, extracting the weight field
from each apple in a list), or grouping data (for example, grouping a list of numbers into
separate lists of even and odd numbers), and so on. The second motivator is that such
operations can often be parallelized. For instance, as illustrated in figure 1.6 , filtering a list on
 
Search WWH ::




Custom Search