Java转义为'this'的引用

nib*_*bsa 5 java concurrency

我开始阅读Java Concurrency in Practice,我遇到了以下示例(这是一个反面的例子 - 显示了不好的做法):

public class ThisEscape {
    public ThisEscape(EventSource source) {
        source.registerListener(new EventListener() {
            public void onEvent(Event e) {
                doSomething(e);
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

书中的作者写道:

当ThisEscape发布EventListener时,它也隐式发布封闭的ThisEscape实例,因为内部类实例包含对封闭实例的隐藏引用.

当我考虑使用这样的代码时,我可以这样做:

EventSource eventSource = new EventSource();
ThisEscape thisEscape = new ThisEscape(eventSource);
Run Code Online (Sandbox Code Playgroud)

我可以获得对已注册的EventListener的引用,但是我能获得对封闭的ThisEscape实例的引用是什么意思?

有人能给我一个这样的行为的例子吗?用例是什么?

fol*_*kol 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();
    }
}
Run Code Online (Sandbox Code Playgroud)