1

Context In this simple code snippet:

public class NewMain1 {

private final ArrayList<Person> myPeople;

public NewMain1() {
    myPeople = new ArrayList<>();
    Person p = new Person("it");
    Person p1 = new Person(this, "it");
    p.setNewMain1(this);
    myPeople.add(p);
}

In Netbeans, the line with the constructor for Person(this, "it") does not get the leaking this warning, but the p.setNewMain1(this) does get the leaking this warning. Is this just an artifact of NetBeans or is it not also a possible leaking this? Passing 'this' in a constructor should have the same dangers as calling a method, right?

  • 1
    Leaking like that is totally possible. I don't use NetBeans, but if it throws a warning for leaking `this` via method, it should apply to constructors as well. Maybe it's an oversight? – Vince May 28 '17 at 23:51
  • I see this pattern in many contexts, where within the constructor other objects are created and 'this' is passed into the constructor. I am wondering if this pattern should have the same concerns as raised in other leaking 'this' discussions. – Manuel Rossetti May 29 '17 at 16:37
  • Yes, it has the same concerns. Passing `this` while in constructor is leaking because the object you are passing can potentially be used before it has been fully constructed. If you moved `myPeople = new ArrayList<>()` to the bottom of constructor, and `Person` tried using it, `myPeople` would still be `null` – Vince May 29 '17 at 18:13
  • It depends on the purpose of the leakage warning. If you only care for multi-threading issues, `new Person(this, "it")` might be fine. – Holger Sep 28 '17 at 11:07

0 Answers0