Java speeds up link to 'this'

I started reading Java Concurrency in practice , and I came across the following example (this is a negative example - it shows bad practice)

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

The author in the book writes:

When ThisEscape publishes an EventListener, it also implicitly publishes an instance of the ThisEscape instance, since instances of the inner class contain a hidden link to the enclosing instance.

When I think about using such code, I could do something like this:

EventSource eventSource = new EventSource();
ThisEscape thisEscape = new ThisEscape(eventSource);

and I can get a link to the registered EventListener, but what does it mean that I could get a link to an instance of ThisEscape?

Can someone give me an example of this behavior? What is the precedent?

+4
source share
1

, , .

:

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

        // Possible Thread Context switch

        // More important initialization
        foo = new Foo();
    }

    public void doSomething(Event e) {
        // Might throw NullPointerException, by being invoked
        // through the EventListener before foo is initialized
        foo.bar();
    }
}
0

Source: https://habr.com/ru/post/1679554/


All Articles