如何一个不可变的对象,非final字段,线程不安全? [英] How can an immutable object, with non-final fields, be thread unsafe?
本文介绍了如何一个不可变的对象,非final字段,线程不安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说我们有这个
// This is trivially immutable.
public class Foo {
private String bar;
public Foo(String bar) {
this.bar = bar;
}
public String getBar() {
return bar;
}
}
继续此问题。
推荐答案
Foo
在安全发布后是线程安全的。例如,这个程序可以打印不安全(它可能不会使用热点/ x86的组合) - 如果你使 bar
final不能发生: / p>
Foo
is thread safe once it has been safely published. For example, this program could print "unsafe" (it probably won't using a combination of hotspot/x86) - if you make bar
final it can't happen:
public class UnsafePublication {
static Foo foo;
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
while (foo == null) {}
if (!"abc".equals(foo.getBar())) System.out.println("unsafe");
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
foo = new Foo("abc");
}
}).start();
}
}
这篇关于如何一个不可变的对象,非final字段,线程不安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文