Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

this pointer escape in Java

Tags:

java

pointers

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);
                }
            }
        );
    }
}
like image 368
KAs Avatar asked Jan 02 '23 16:01

KAs


2 Answers

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.

like image 93
Karol Dowbecki Avatar answered Jan 13 '23 21:01

Karol Dowbecki


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.

like image 34
hagrawal Avatar answered Jan 13 '23 20:01

hagrawal