在Java并发实践第3章中,作者建议不要共享可变状态。此外,他还补充说,下面的代码不是共享状态的好方法。
class UnsafeStates {
private String[] states = new String[] {
"AK", "AL"
};
public String[] getStates() {
return states;
}
}
摘自书中:
Publishing states in this way is problematic because any caller can modify its contents. In this case, the states array has escaped its intended scope, because what was supposed to be private state has been effectively made public.
我的问题是:我们经常使用 getter 和 setter 来访问类级别的私有(private)可变变量。如果这不是正确的方法,那么共享状态的正确方法是什么?封装的正确方法是什么states
?
最佳答案
对于原始类型,int
、float
等,使用像这样的简单 getter 不允许调用者设置其值:
someObj.getSomeInt() = 10; // error!
但是,对于数组,您可以从外部更改其内容,根据具体情况,这可能是不可取的:
someObj.getSomeArray()[0] = newValue; // perfectly fine
这可能会导致字段被代码的其他部分意外更改的问题,从而导致难以跟踪的错误。
您可以做的是返回数组的副本:
public String[] getStates() {
return Arrays.copyOf(states, states.length);
}
这样,即使调用者改变了返回数组的内容,对象所持有的数组也不会受到影响。
关于java - 共享可变状态有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58729837/