What are the different ways in which 'this' can hide in Java?

There is a question about stack overflow, why starting a thread inside the constructor is not a good idea . I realized that the result of such a thing would be that 'this' could escape. I also read that posting EventListener from the constructor is also a bad idea for the same reason. What are the other patterns I should be aware of in which 'this' might go away?

+5
source share
1 answer

Call any instance method of your object from the leak constructor thison this mathod. This may be OK, as long as this method is under your control (is not publicly available), and you make sure that you do not miss thisfurther from it. Using thisas an argument for any method is, of course, a more explicit option, and this happens when you speak x.addEventListener(this). Perhaps more intriguing, since the less obvious way to leak thisis to not use thisthe argument itself, but an instance of an internal / 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
  }
}

this , . , , static, .

+4

All Articles