Skip to content
Advertisement

this pointer escape in Java

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);
                }
            }
        );
    }
}

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement