I am reading the book Java concurrency in practice, in section 3.2 , it gives the following code example to illustrate implicitly allowing the this reference to escape (Don’t do this, especailly in constructor) :
public class ThisEscape { public ThisEscape(EventSource source) { source.registerListener ( new EventListener() { public void onEvent(Event e) { doSomething(e); } } ); } } The book then says :
When
ThisEscapepublishes theEventListener, it implicitly publishes the enclosingThisEscapeinstance as well, because inner class instances contain a hidden reference to the enclosing instance.
I understand the above words from Java's perspective, but I can't come up with a example how could the above code's EventListener escaping enclosing reference this be harmful? In what way?
For example, if I create a new instance of ThisEscape:
ThisEscape myEscape = new Escape(mySource); Then, what? How is it harmful now? In which way it is harmful?
Could someone please use above code as the base and explain to me how it is harmful?
======= MORE ======
The book is trying to say something like the anonymous EventListener holds a hidden reference to the containing class instance which is not yet fully constructed. I want to know in example, how could this un-fully constructed reference be misused, and I prefer to see a code example about this point.
The book gives a right way of doing things, that's to use a static factory method as below:
public static SafeListener newInstance(EventSource source) { SafeListener safe = new SafeListener(); source.registerListener (safe.listener); return safe; } I just don't get the point of the whole thing.