Why is shared mutability bad?

Viewed 8479

I was watching a presentation on Java, and at one point, the lecturer said:

"Mutability is OK, sharing is nice, shared mutability is devil's work."

What he was referring to is the following piece of code, which he considered an "extremely bad habit":

//double the even values and put that into a list.
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 1, 2, 3, 4, 5);
List<Integer> doubleOfEven = new ArrayList<>();

numbers.stream()
       .filter(e -> e % 2 == 0)
       .map(e -> e * 2)
       .forEach(e -> doubleOfEven.add(e));

He then proceeded writing the code that should be used, which is:

List<Integer> doubleOfEven2 =
      numbers.stream()
             .filter(e -> e % 2 == 0)
             .map(e -> e * 2)
             .collect(toList());

I don't understand why the first piece of code is "bad habit". To me, they both achieve the same goal.

4 Answers

In the first example, if you were to use parallel(), you’d have no guarantee of the insertions (multiple threads inserting the same element for example).

collect(...) on the other hand, when run in parallel, splits the work and internally collects the results in an intermediate step and then adds them to the final list, ensuring order and safety.

Related