0

I have an inner helper class, and I would like to add each new instance of it to a map in the containing class, like this:

public class SomeService {
    private final Map<Integer, ServiceTask> pendingTasksByKey;

    private class ServiceTask {
        private ServiceTask(int key) {
            // initialization...
            pendingTasksByKey.put(key, this);
        }
    }

    // the rest of the code follows
}

When I do it, NetBeans complains about using this in the constructor. OK, I get it, it's a dangerous practice in the general case because someone could extend my class and then I would be leaking this referring to an incompletely initialized object. I didn't want to turn off this warning, so I thought that I could make the class final. This way no one would be able to extend my class, and therefore it should be pretty safe to use this, as the initialization is complete as this point. But NetBeans still shows the warning even if I mark the inner class as final.

Am I right or is there something I missed? Is it just NetBeans being too picky? Besides possible multi-threading memory model issues I can't think of any dangers of such this usage.

Sergei Tachenov
  • 24,345
  • 8
  • 57
  • 73

2 Answers2

2

It's a Netbeans-specific warning. It is a reminder that the object is not yet constructed so it could be a problem. If you aren't doing anything where that will be a problem then you can ignore it. For example look at this code:

class A {
    public Object obj;

    public A() {
        B b = new B();
        b.addMe(this);

        obj = new Object();
    }
}

class B {
    ArrayList<A> list = new ArrayList<A>(0);

    public void addMe(A a) {
        list.add(a);
        System.out.println(a.obj.toString());
    }
}

This code has a problem and I should not ignore the "leaking this in constructor" warning.

Radiodef
  • 37,180
  • 14
  • 90
  • 125
  • In this example it's pretty clear. It doesn't even need the warning. I think the warning was meant to remind about possible subclassing, so that even if you leak this in the last statement of the constructor, the object can still be not completely initialized. But in a final class there should be no such problem. NetBeans could check if all the fields are initialized by the point you leak "this" and issue a warning only if they aren't. – Sergei Tachenov Oct 26 '13 at 05:55
  • @SergeyTachenov Yes it's not the best example of why this can potentially be a problem. It is just an example of where using this results in an exception being thrown. There are probably better examples I'm sure. This is the just the first that I thought of that's visually obvious. – Radiodef Oct 26 '13 at 18:45
0

Leaking this in constructor warning has a discussion of this Netbeans warning.

If pendingTasksByKey has a corresponding remove somewhere during the life cycle of these classes I'd say you are right, Netbeans is being picky.

Community
  • 1
  • 1
Drew MacInnis
  • 8,267
  • 1
  • 22
  • 18