您的位置:首页 > 其它

【翻译五】旧内存模型有什么问题

2017-03-21 00:00 169 查看
摘要: 原文地址http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html

What was wrong with the old memory model?

There were several serious problems with the old memory model. It was difficult to understand, and therefore widely violated. For example, the old model did not, in many cases, allow the kinds of reorderings that took place in every JVM. This confusion about the implications of the old model was what compelled the formation of JSR-133.

旧的内存模型有一些严重的问题,也非常难理解,因此总被违反。举个栗子,多数情况下,旧模型不允许任何JVM中发生重排序。但实际上重排序又是存在的,正是这种混乱,促使了JSR-133的编制。

One widely held belief, for example, was that if final fields were used, then synchronization between threads was unnecessary to guarantee another thread would see the value of the field. While this is a reasonable assumption and a sensible behavior, and indeed how we would want things to work, under the old memory model, it was simply not true. Nothing in the old memory model treated final fields differently from any other field -- meaning synchronization was the only way to ensure that all threads see the value of a final field that was written by the constructor. As a result, it was possible for a thread to see the default value of the field, and then at some later time see its constructed value. This means, for example, that immutable objects like String can appear to change their value -- a disturbing prospect indeed.

再举个栗子,在旧的内存模型下的多线程中,如果使用了final字段,就没必要使用synchronized来保证该字段的可见性了。但这只是个合理的假想,也是个合理的做法,事实上,这与我们想要的程序完全不同。旧内存模型下,final字段与其他字段没有任何不同,这意味着,在构造方法中赋值的final字段,必须用同步来保证其对其他线程的可见性。因此,在旧的内存模型下,当对象正在构建时,其他线程会先看到对象中final字段的默认值,然后会看到它在构造方法中被赋予的值,这意味着,本应不可变的对象的值却会改变,例如String。确实好乱。

The old memory model allowed for volatile writes to be reordered with nonvolatile reads and writes, which was not consistent with most developers intuitions about volatile and therefore caused confusion.

旧内存模型允许volatile字段的写入和非volatile字段的读写发生重排序,这与大多开发者对volatile的直觉不一致,因此也会产生疑惑。
此处大概是这样的

volatile int a = 1;
int b = 0;

//b可能是1,也可能是0
b = ++a;

Finally, as we shall see, programmers' intuitions about what can occur when their programs are incorrectly synchronized are often mistaken. One of the goals of JSR-133 is to call attention to this fact.

最终,正如我们看到的,程序员对未正确同步的程序运行的直观判断经常是错的,JSR-133的其中一个目的,就是为了引起程序员们对这个事实的注意。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: