Java: reference escape

后端 未结 4 567
北荒
北荒 2020-12-07 11:38

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 t

4条回答
  •  旧时难觅i
    2020-12-07 12:32

    My guess is that doSomething method is declared in ThisEscape class, in which case reference certainly can 'escape'.
    I.e., some event can trigger this EventListener right after its creation and before execution of ThisEscape constructor is completed. And listener, in turn, will call instance method of ThisEscape.

    I'll modify your example a little. Now variable var can be accessed in doSomething method before it's assigned in constructor.

    public class ThisEscape {
        private final int var;
    
        public ThisEscape(EventSource source) {
            source.registerListener(
                new EventListener() {
                    public void onEvent(Event e) {
                        doSomething(e);
                    }
                }
            );
    
            // more initialization
            // ...
    
            var = 10;
        }
    
        // result can be 0 or 10
        int doSomething(Event e) {
            return var;
        }
    }
    

提交回复
热议问题