假设我有一个需要配置、依赖注入等的类。
public class MyClass {
private String someConfig;
private SomeMutableClass anotherConfig;
MyClass() {
// impractical to set everything in ctor
// otherwise I'd declare someConfig final and
// not worry about MT safety.
}
void setConfig(cfg) {
this.someConfig = cfg;
}
void anotherConfig(cfg) {
this.anotherConfig = cfg;
}
...
// below is code that uses the config set before, possibly by
// multiple threads.
}
这是一个人为的例子,但是如果我不能轻松地完成 ctor 中的所有配置怎么办?假设配置在执行早期完成并且不会更改。严格来说,由于内存模型,我必须同步所有对 someConfig 的引用。这个要求在实践中可以放宽吗?