为什么共享可变性不好? [英] Why is shared mutability bad?

查看:109
本文介绍了为什么共享可变性不好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在观看关于Java的演讲,有一次,讲师说:

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.

推荐答案

执行并行处理时问题就出现了。前一阵子我读了 Henrik Eichenhardt的博客回答 为什么共享的可变状态是所有邪恶的根源。

The problem comes into play when performing parallel processing. A while back I read a blog by Henrik Eichenhardt answering as to why a shared mutable state is the root of all evil.

这是一个简短的推理,为什么共享可变性好;从博客中提取。

This is a short reasoning as to why shared mutability is not good; extracted from the blog.


非确定性=并行处理+可变状态

这个等式基本上意味着并行处理和
可变状态组合导致非确定性程序行为
如果您只是进行并行处理并且只有不可变状态
一切都很好并且很容易推理程序。另一方面,如果你想用可变数据进行并行处理,
需要同步对可变变量的访问,
实际上是将程序的这些部分单线程化。这不是什么新鲜事,但我没有看到这些概念如此优雅地表达出来。 非确定性程序被破坏

This equation basically means that both parallel processing and mutable state combined result in non-deterministic program behaviour. If you just do parallel processing and have only immutable state everything is fine and it is easy to reason about programs. On the other hand if you want to do parallel processing with mutable data you need to synchronize the access to the mutable variables which essentially renders these sections of the program single threaded. This is not really new but I haven't seen this concepts expressed so elegantly. A non-deterministic program is broken.

此博客继续推导内部细节,了解原因没有正确同步的并行程序会被破坏,您可以在附加的链接中找到它们。

This blog goes on to derive the inner details as to why parallel programs without proper synchronization are broken, which you can find within the appended link.

这篇关于为什么共享可变性不好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆