Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
225 views
in Technique[技术] by (71.8m points)

java - Allowing the this reference to escape

I would appreciate help in understanding the following from 'Java Concurrency in Practice':

Calling an overrideable instance method(one that is neither private nor final) from the constructor can also allow the this reference to escape.

  1. Does 'escape' here simply mean that we may probably be calling an instance method,before the instance is fully constructed?
    I do not see 'this' escaping the scope of the instance in any other way.
  2. How does 'final' prevent this from happening?Is there some aspect of 'final' in instance creation that I am missing?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  1. It means calling code outside the class, and passing this.
    That code will assume that the instance is fully initialized, and may break if it isn't.
    Similarly, your class might assume that some methods will only be called after the instance is fully initialized, but the external code is likely to break those assumptions.

  2. final methods cannot be overridden, so you can trust them to not pass this around.
    If you call any non-final method in the constructor for a non-final class, a derived class might override that method and pass this anywhere.
     
    Even when you call final methods, you still need to make sure that they are safely written – that they do not pass this anywhere, and that themselves don't call any non-final methods.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...