4

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);
                }
            }
        );
    }
}
David Brossard
  • 13,584
  • 6
  • 55
  • 88
KAs
  • 1,818
  • 4
  • 19
  • 37
  • 4
    The anonymous inner class closes over a reference to `this` and implicitly uses it in the call to `doSomething` which I assume is intended to be an instance method. – Daniel Pryden Mar 12 '18 at 13:14

2 Answers2

7

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.

Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
2

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.

hagrawal7777
  • 14,103
  • 5
  • 40
  • 70