Java: reference escape

Viewed 8025

Read that the following code is an example of "unsafe construction" as it allows this reference to escape. I couldn't quite get how 'this' escapes. I am pretty new to the java world. Can any one help me understand this.

public class ThisEscape {
    public ThisEscape(EventSource source) {
        source.registerListener(
            new EventListener() {
                public void onEvent(Event e) {
                    doSomething(e);
                }
            });
    }
}
5 Answers

This confused me quite a bit, as well. Looking at the full code example and also just reading it a million times helped me finally see it. Compliments to Stephen C, though, whose answer is quite thorough and offers a simplified example.

The problem is source.registerListener(), which is provided as a member of ThisEscape. Who knows what that method does? We don't. ThisEscape doesn't specify, because it's declared in an interface within ThisEscape.

public class ThisEscape {
    // ...
    
    interface EventSource {
        void registerListener(EventListener e);
    }

    interface EventListener {
        void onEvent(Event e);
    }

    // ...
}

Whatever class implements EventSource provides the implementation for registerListener() and we have no idea what it might do with the provided EventListener. But, because EventListener is a part of ThisEscape, it also contains a hidden reference to it. That's why this example is so tricky. Basically, while ThisEscape is being constructed, a reference to it is published via source.registerListener(<reference>), and who knows what that EventSource will do with it.

It's one of the many great cases for a private constructor and static factory method. You can confine construction to one line in the static factory method, ensuring its completion before passing it to source.

Related