本文介绍了允许 this 引用转义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您能从Java 并发实践"中理解以下内容,我将不胜感激:

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

调用可覆盖的实例方法(既不是来自构造函数的私有或最终)也可以允许此引用转义.

  1. 这里的转义"是否仅仅意味着我们可能在实例完全构造之前调用了一个实例方法?
    我没有看到这个"以任何其他方式逃离实例的范围.
  2. final"如何防止这种情况发生?在实例创建中是否存在我遗漏的final"方面的内容?

推荐答案

  1. 表示在类外调用代码,并传递this.
    该代码将假定该实例已完全初始化,否则可能会中断.
    同样,您的类可能假设某些方法仅在实例完全初始化后才会被调用,但外部代码可能会破坏这些假设.

  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.

final 方法不能被覆盖,因此您可以相信它们不会传递 this.
如果在非final 类的构造函数中调用任何非final 方法,派生类可能会覆盖该方法并将this 传递到任何地方.
 
即使当你调用 final 方法时,你仍然需要确保它们被安全地编写 –他们不会在任何地方传递 this,并且他们自己不会调用任何非 final 方法.

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.

这篇关于允许 this 引用转义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-18 17:04