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 ?
Share
Calling any instance method of your object from the constructor leaks
thisto 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 leakthisfurther out from it. Usingthisas an argument to any method is, of course the more explicit variant, and that happens when you sayx.addEventListener(this). A perhaps more insdidious, since less obvious, way to leak athisis to not usethisitself as an argument, but an instance of an inner/local/anonymous class, sayIn all these cases
thiswill be the enclosing instance of the object passed as a method argument. If, on the other hand, you declare astaticnested class, it will not have an enclosing instance.