I was looking around but I can't find a definitive answer about assigning this
in a private field is an anti-pattern in Java. Consider the example below of a singleton-based pattern:
public class Foo {
private static Foo INSTANCE;
private Foo() {
INSTANCE = this;
}
}
My guess is that at the time of the declaration,
this
is not fully initialised so it's not safe as if any other call would use thestatic
field it might find an instance that it's not fully initialised.
Is that correct though? Is this something that we should avoid? If yes, why? Is there any way to make sure that those calls are safe (as in that we don't use INSTANCE
any further in the constructor)?