When reading < Java Concurrency in Practice >, there's an example saying that the following code snippet will lead to this
pointer escape in the constructor method. But I'm not sure what exactly does it mean, since I couldn't see any this
reference in the source code of ThisEscape
constructor method. Any ideas? Thanks.
public class ThisEscape {
public ThisEscape(EventSource source) {
source.registerListener(
new EventListener() {
public void onEvent(Event e) {
doSomething(e);
}
}
);
}
}
EventListener
object is created from an anonymous class and will have access to ThisEscape.this
reference. Because of that the this
pointer "escapes" the scope of the class it belongs to and will be accessible in other places like EventListener
.
Even worse this whole thing happens before ThisEscape
is fully constructed so the doSomething()
method can potentially be called before the constructor finishes if the event is dispatched and handled by another thread.
Not sure what's written in "< Java Concurrency in Practice >" but you can read this article's "Don't implicitly expose the "this" reference
" section which explain it well using same example/concept.
Basically this example is about "implicitly" exposing the this
reference, and in the example it happens because "non-static" inner classes maintain an implicit copy of the this reference of their parent object. So, in your example, under multi-threading scenarios, it is possible that doSomething(e)
method can get called even before object creation is completed.
This answer explains how inner class maintains an implicit reference to parent class.
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