Functional Programming: Immutability and Concurrency
Explore how Java 8 introduces functional programming concepts focused on immutability to avoid shared mutable state. Learn to leverage concurrency using parallel streams and CompletableFuture for efficient thread-safe computations, enhancing Java applications with clearer and safer code patterns.
We'll cover the following...
Immutability
In functional programming, state is considered harmful and avoided whenever possible. Instead, immutable (unchangeable) data structures are preferred. For example, String is an immutable type in Java.
As we may have learned, Java 8’s new Date/Time classes are immutable. What we may not have realized is that almost everything added in Java 8 is immutable (Optional and Streams for example).
However, we need to be careful when using Java 8’s new functional patterns. That is, to not accidentally fall back into the mutable mind-set. For example, the following type of code should be avoided:
int[] myCount = new int[1];
list.forEach(dragon -> {
if (dragon.isGreen()) myCount[0]++;
}
...