这种流利的类并不严格不变,因为这些字段不是最终的,但是它是线程安全的,为什么?像使用clone()和非final字段的类一样流畅的线程安全
我关心的线程安全问题不是竞争条件,而是变量的可见性。我知道有一个使用最终变量和构造函数而不是clone()+赋值的解决方法。我只想知道这个例子是否可行。
public class IsItSafe implements Cloneable {
private int foo;
private int bar;
public IsItSafe foo(int foo) {
IsItSafe clone = clone();
clone.foo = foo;
return clone;
}
public IsItSafe bar(int bar) {
IsItSafe clone = clone();
clone.bar = bar;
return clone;
}
public int getFoo() {
return foo;
}
public int getBar() {
return bar;
}
protected IsItSafe clone() {
try {
return (IsItSafe) super.clone();
} catch (CloneNotSupportedException e) {
throw new Error(e);
}
}
}
通过制作IsItSafe final,您可以使这个更安全一些。你是否担心有人用反射改变foo或bar?你为什么关心他们的知名度? – alpian 2012-03-08 17:59:15
我并不担心有人通过反思或扩展课程来改变这个领域。我在问,因为我设计了一个类似的课程,其线程安全性受到了质疑。 – 2012-03-08 18:09:31
仅供参考,我在这里发布了这个问题的延续:http://stackoverflow.com/questions/9633771/how-can-one-break-this-non-thread-safe-object – assylias 2012-03-09 12:04:32