Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the various ways by which the 'this' can escape in Java?

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 ?

like image 974
Inquisitive Avatar asked Oct 07 '22 09:10

Inquisitive


1 Answers

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.

like image 109
Marko Topolnik Avatar answered Oct 12 '22 12:10

Marko Topolnik