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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With