search

Home  >  Q&A  >  body text

java如何理解隐式地使this引用逸出

这是《Java并发编程实战》3.2发布与逸出一节中的示例代码。我无法理解,this是怎么逸出的。

//隐式地使this引用逸出(不要这么做)
public class ThisEscape {
    public ThisEscape(EventSource source){
        source.registerListener(new EventListener() {
            public void onEvent(Event e){
                doSomething(e);
            }
        });
    }
}

书上说,当ThisEscape发布EventListener时,也隐含地发布了ThisEscape实例本身,因为在这个内部类的实例中包含了对ThisEscape实例的隐含引用。

PHPzPHPz2766 days ago840

reply all(1)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-18 10:33:22

    To be honest, I don’t know much about multi-threading and escape, but I understand inner classes, so I can give you a strong answer. Both inner classes and anonymous inner classes can access the fields of objects of outer classes. Why is this happening? Actually, it’s because When the inner class is constructed, the object this of the outer class will be implicitly passed as a parameter to the constructor of the inner class. This work is done by the compiler. It will add this parameter to all the constructors of your inner class, so The anonymous inner class in your example implicitly passes the object created by ThisEscape to the anonymous inner class when you construct ThisEscape. I don't know what problems this will cause. It seems that I am afraid that onEvent will operate the private domain of the external class? I need you to teach me this part

    reply
    0
  • Cancelreply