I am using the NetBeans IDE and it is giving me a warning that does not make sense to me. The warning states “Leaking this in constructor”. The following code is the basic setup (I just removed code irrelevant to the issue). Basically I just want to keep a list of all Square objects made. Is this a warning I need to worry about? Or is it just the possible cause of a memory leak depending on the situation?
Either way, can someone explain why this would be considered a leak?
public class Square {
private static ArrayList<Square> squares;
public Square() {
if(squares == null) {
squares = new ArrayList<>();
}
squares.add(this); // I get a warning on this line
}
}
I know it is just a warning, but I don’t like to ignore warnings unless I fully understand what is going on and can make the informed choice for a specific situation.
Thanks!
I don’t think the warning concerns garbage collection, although that is indeed a problem here. The instances will never be GC’ed (unless the whole
ClassLoaderis collected).The warning is saying that
thisis being passed to another method from within the constructor. Before the constructor finishes,thisis not necessarily a fully-formed and initialized object according to the logic enshrined in the constructor. Anything in the constructor is intended to happen before anything else gets its hands on the object. But something else is getting to usethisbefore the constructor finishes. That could cause surprising bugs.