Functional Programming: Immutability and Concurrency

Learn about immutability and concurrency in Java 8.

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]++;
}

You may think you are being clever, but this can cause problems. Instead, you should do something like the following:

list.stream().filter(Dragon::isGreen).count();

If you ever find yourself resorting to mutability, consider if you could use some combination of filter, map, reduce, or collect instead.

Concurrency

Get hands-on with 1200+ tech skills courses.