5

There is a question on Stack Overflow on why starting a thread inside the constructor is not a good idea . I realised that the result of such a thing will be that 'this' can escaped.I also read that publishing a EventListener from constructor is also a bad idea for the same reason . What are the other patterns which I should be aware of in which 'this' can escape ?

Community
  • 1
  • 1
Inquisitive
  • 7,476
  • 14
  • 50
  • 61
  • 1
    A key distinction is that 'this' escapes in a partial state before it is allowed to be completely constructed. – phatfingers Jun 30 '12 at 16:45

1 Answers1

4

Calling any instance method of your object from the constructor leaks this to that mathod. This may be OK as long as that method is under your control (not publicly overridable), and you are making sure you don't leak this further out from it. Using this as an argument to any method is, of course the more explicit variant, and that happens when you say x.addEventListener(this). A perhaps more insdidious, since less obvious, way to leak a this is to not use this itself as an argument, but an instance of an inner/local/anonymous class, say

public class Main 
{
  private class MyListener extends MouseAdapter { ...}

  public Main() {
    class Listener1 extends MouseAdapter { ... }
    someSwingComponent.addMouseListener(new MyListener()); // inner class
    someSwingComponent.addMouseListener(new Listener1()); // local class
    someSwingComponent.addFocusListener(new FocusAdapter() { ... }); // anonymous
  }
}

In all these cases this will be the enclosing instance of the object passed as a method argument. If, on the other hand, you declare a static nested class, it will not have an enclosing instance.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
  • So can I assume that 'this' can leaked whenever 'this' is passed as an argument to an alien method(To a Class 'Foo' an alien methods are ones that it has no control over and it can mean methods of other classes or non private/overrideable methods of C itself)? – Inquisitive Jun 30 '12 at 18:48
  • I see I didn't make my point clear enough in the first sentence. I meant "any instance method of `this` object" (the one whose constructor is being executed). As far as alien methods, their access level doesn't matter. What matters is whether you are passing `this` to such a method---either explicitly or implicitly through an inner class instance. – Marko Topolnik Jun 30 '12 at 18:58