我理解,出于线程安全考虑,不应在构造函数中转义“this”引用,其中对象尚未完全构造,而是“泄漏”到其他对象。例如
public class TestClass{
public TestClass(){
StaticClass.addListener(this);
}
}
如果我在另一个构造函数中调用默认构造函数,是否可以保证构造对象的完整性并避免任何“this”引用转义问题?
public class TestClass{
public TestClass(){
}
public TestClass(String str){
this();
StaticClass.addListener(this);
}
}
最佳答案
简而言之,是的,在构造完成之前,也就是在达到新的 Java 5 内存模型的构造内存边界之前,您的 this
引用仍然会泄漏。您需要在新语句之后添加监听器,而不是从构造序列中的任何位置添加监听器:
TestClass obj=new TestClass();
StaticClass.addListener(obj);
或
StaticClass.addListener(new TestClass());
关于java - 在这种情况下, 'this' 引用会从构造函数中转义吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4020588/