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
thisreference 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:or