For thread-safety reasons it is argumented:
Do not allow the this reference to escape during construction.
But is this always an issue and should be avoided by using newInstance() methods? Inside my model class I have a TableModel which should be instantiated, within the model class, but which also requires a reference to the model class:
public class MainModel {
TableModel tableMode;
public MainModel() {
tableModel = new MyTableModel(this);
}
}
If the constructor does not use this right away is it then safe or should it be avoided in any means?
If nothing in the
MyTableModelis going to do anything in other threads etc – or copy the variable to some other shared data, such as a static variable – then it’s safe.Of course, if
MyTableModelstarts calling methods on theMainModelreference within its constructor, then it’ll be calling them on a not-completely-initialized-yet object, which can cause issues – but that’s not really threading related.I blogged a bit more on this a while ago.