Will 'this' reference escape from Constructor in this case?
I understand that 'this' reference should not be escaped in Constructor due to thread safety concern, where the object is not yet completely constructed but 'leaked' out to other objects. For instance
public class TestClass{
public TestClass(){
StaticClass.addListener(this);
}
}
If I invoke the default constructor in another constructor, does that guarantee the integrity of the constructed object and avoid any 'this' reference escape issues?
public class TestClass{
public TestClass(){
}
public TestClass(String str){
this();
开发者_运维百科 StaticClass.addListener(this);
}
}
In short, yes, your this
reference is still leaked before construction is complete, and thus before the new Java 5 memory model's memory boundary for construction is reached. You need to add the listener after your new statement, and not from anywhere in the construction sequence:
TestClass obj=new TestClass();
StaticClass.addListener(obj);
or
StaticClass.addListener(new TestClass());
精彩评论