Why is shared mutability bad?

前端 未结 4 1150
南方客
南方客 2020-12-12 22:14

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.\"

4条回答
  •  囚心锁ツ
    2020-12-12 22:34

    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.

提交回复
热议问题