【发布时间】:2023-03-19 11:53:01
【问题描述】:
这个类似流利的类并不是严格不可变的,因为字段不是最终的,但它是线程安全的,为什么?
我关心的线程安全问题不是竞争条件,而是变量的可见性。我知道有一种使用最终变量和构造函数而不是 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 设置为最终版本来稍微安全一些。您是否担心有人通过反射改变 foo 或 bar?您为什么担心他们的知名度?
-
我不担心有人通过反射或扩展类来修改字段。我问是因为我设计了一个类似的类,它的线程安全性受到了质疑。
-
仅供参考,我在这里发布了问题的延续:stackoverflow.com/questions/9633771/…
标签: java thread-safety fluent-interface