允许此引用转义 [英] Allowing the this reference to escape
问题描述
我会感谢您帮助理解Java并发实践中的以下内容:
I would appreciate help in understanding the following from 'Java Concurrency in Practice':
调用可覆盖的实例方法既不是
private也不是final)从构造函数中也可以允许
这个引用转义。
Calling an overrideable instance method(one that is neither private nor final) from the constructor can also allow the this reference to escape.
- 这里的'escape'只是意味着我们可能在实例被完全构造之前调用一个实例方法?
我看不到'this'转义实例的范围任何其他方式。 - 'final'如何防止这种情况发生?在实例创建中,我缺少final的某些方面?
推荐答案
-
,并传递
this
。
该代码将假定实例已完全初始化,如果不是,则可能会中断。
类似地,你的类可能假设一些方法只会在实例完全初始化后被调用,但外部代码很可能会破坏这些假设。
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.
最终
方法不能被覆盖,因此您可以信任它们不会通过此
。
如果在非< - code>最终类的构造函数中调用任何非< - code>最终方法,派生类可能会覆盖
即使在调用 final $时也是如此。
c $ c>方法,你仍然需要确保他们安全地写–它们不会在任何地方传递
方法。 > this
,并且它们自己不调用任何非< - code>最终
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.
这篇关于允许此引用转义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!