Java Reference
In-Depth Information
1.1.4. Parallelism and shared mutable data
The third programming concept is rather more implicit and arises from the phrase “parallelism
almost for free” in our previous discussion on stream processing. What do you have to give up?
You may have to make some small changes in the way you code the behavior passed to stream
methods. At first, these changes might feel a little uncomfortable, but once you get used to them,
you'll love them. You must provide behavior that is safe to execute concurrently on different
pieces of the input. Typically this means writing code that doesn't access shared mutable data to
do its job. Sometimes these are referred to as pure functions or side-effect-free functions or
stateless functions, and we'll discuss these in detail in chapters 7 and 13 . The previous
parallelism arises only by assuming that multiple copies of your piece of code can work
independently. If there's a shared variable or object, which is written to, then things no longer
work: what if two processes want to modify the shared variable at the same time? ( Section 1.3
gives a more detailed explanation with a diagram.) You'll find more about this style throughout
the topic.
Java 8 streams exploit parallelism more easily than Java's existing Threads API, so although it's
possible to use synchronized to break the no-shared-mutable-data rule, it's fighting the system
in that it's abusing an abstraction optimized around that rule. Using synchronized across
multiple processing cores is often far more expensive than you expect, because synchronization
forces code to execute sequentially, which works against the goal of parallelism.
Two of these points (no shared mutable data and the ability to pass methods and
functions—code—to other methods) are the cornerstones of what's generally described as the
paradigm of functional programming, which you'll see in detail in chapters 13 and 14 . In
contrast, in the imperative programming paradigm you typically describe a program in terms
of a sequence of statements that mutate state. The no-shared-mutable-data requirement means
that a method is perfectly described solely by the way it transforms arguments to results; in
other words, it behaves as a mathematical function and has no (visible) side effects.
1.1.5. Java needs to evolve
You've seen evolution in Java before. For example, the introduction of generics and using
List<String> instead of just List may initially have been irritating. But you're now familiar with
this style and the benefits it brings (catching more errors at compile time and making code
easier to read, because you now know what something is a list of).
Other changes have made common things easier to express, for example, using a for-each loop
instead of exposing the boilerplate use of an Iterator. The main changes in Java 8 reflect a move
 
Search WWH ::




Custom Search