如何通过发布内部类实例引用外部类转义? [英] How does `this` reference to an outer class escape through publishing inner class instance?

查看:152
本文介绍了如何通过发布内部类实例引用外部类转义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题略有不同。但要求是/否回答,但我正在寻找这本书(Java并发在实践中)缺少的解释,这个明显的大错误如何被恶意或意外利用。


发布对象或其内部状态可能是
的最终机制是发布内部类实例,如图所示in
ThisEscape在Listing 3.7中。当ThisEscape发布
EventListener时,它也隐式地发布包围的ThisEscape
实例,因为内部类实例包含一个隐藏的
引用包含的实例
p>

清单3.7。隐式允许此引用脱离。不要
这样做。




  public class This Escape {
public ThisEscape(EventSource source){
source.registerListener(
new EventListener(){
public void onEvent(Event e){
doSomething(e);
}
});
}
}




安全施工实践



ThisEscape说明了一个重要的特殊情况下的逃生 - 当
这个引用在建设过程中逃脱。当内部
EventListener实例被发布时,封装的ThisEscape
实例也是如此。但是一个对象在它的构造函数返回后只有一个可预测的,一致的状态
,所以从它的
构造函数中发布一个对象可以发布一个不完全构造的对象。这是
true,即使发布是构造函数中的最后一个语句。
如果这个引用在构造过程中被转义,那么对象是
被认为没有正确构造。[8]



[8]引用不应该从
线程中转义,直到构造函数返回之后。这个引用可以是
存储在某处的构造函数,只要它不被
另一个线程使用,直到构造。清单3.8中的SafeListener
使用此技术。



不允许此引用在构造期间转义。


在完成构建之前,有人会如何编写代码来访问OuterClass? 隐藏的内部类引用在第一段中用斜体表示?

解决方案

请参阅这篇文章。这里清楚地解释了当你让 this escape。



这里是一个后续与进一步解释。



这是Heinz Kabutz惊人的通讯,讨论这个和其他非常有趣的话题。我强烈推荐它。



下面是从链接中获取的示例,其中显示了此 c>参考转义:

  public class ThisEscape {
private final int num;

public ThisEscape(EventSource source){
source.registerListener(
new EventListener(){
public void onEvent(Event e){
doSomething e);
}
});
num = 42;
}

private void doSomething(Event e){
if(num!= 42){
System.out.println(Race condition detected at+
new Date());
}
}
}




当它被编译时,javac生成两个类。外部类如下所示:




  public class ThisEscape {
private final int num;

public ThisEscape(EventSource source){
source.registerListener(new ThisEscape $ 1(this));
num = 42;
}

private void doSomething(Event e){
if(num!= 42)
System.out.println(
at+ new Date());
}

static void access $ 000(ThisEscape _this,Event event){
_this.doSomething(event);
}
}




匿名内部类:




  class ThisEscape $ 1 implements EventListener {
final ThisEscape this $ 0 ;

ThisEscape $ 1(ThisEscape thisescape){
this $ 0 = thisescape;
super();
}

public void onEvent(Event e){
ThisEscape.access $ 000(this $ 0,e);
}
}

这里的匿名内部类在外部类被转换为一个包访问类,它接收对外部类的引用(允许 this 转义的类)。为了让内部类能够访问外部类的属性和方法,在外部类中创建一个静态包访问方法。这是访问$ 000



这两篇文章显示实际的转义如何发生和可能发生。 p>

什么基本上是一个竞争条件,可能导致 NullPointerException 或任何其他异常时,尝试使用对象,但尚未完全初始化。在这个例子中,如果一个线程足够快,它可能会运行 doSomething()方法,而 num 尚未正确初始化为 42



编辑:
关于如何针对此问题进行编码的几行/功能缺失。我只能考虑坚持一套(可能不完整的)规则/原则来避免这个问题和其他人:




  • code> private 方法

  • 如果你喜欢肾上腺素,想调用 protected 方法从构造函数中执行,但是这些方法声明为 final ,以便它们不能被子类覆盖

  • strong>从不在构造函数中创建内部类,即匿名,本地,静态或非静态

  • 在构造函数中,不要传递 this c>直接作为任何参数

  • 避免上述规则的任何传递组合,即不要在中创建一个匿名内部类,

  • 使用构造函数只是构造一个构造函数。


如果您需要使用此类的实例,则只能使用默认值或提供的参数初始化类的属性。做其他事情,使用构建器或工厂模式。


This was asked slightly differently earlier but asking for a yes/no answer but I'm looking for the explanation that's missing from the book (Java Concurrency in Practice), of how this apparent big mistake would be exploited maliciously or accidentally.

A final mechanism by which an object or its internal state can be published is to publish an inner class instance, as shown in ThisEscape in Listing 3.7. When ThisEscape publishes the EventListener, it implicitly publishes the enclosing ThisEscape instance as well, because inner class instances contain a hidden reference to the enclosing instance.

Listing 3.7. Implicitly Allowing the this Reference to Escape. Don't do this.

public class This Escape {
    public ThisEscape(EventSource source) {
        source.registerListener(
            new EventListener() {
                public void onEvent(Event e) {
                    doSomething(e);
                }
            });
    }
}

3.2.1. Safe Construction Practices

ThisEscape illustrates an important special case of escape—when the this references escapes during construction. When the inner EventListener instance is published, so is the enclosing ThisEscape instance. But an object is in a predictable, consistent state only after its constructor returns, so publishing an object from within its constructor can publish an incompletely constructed object. This is true even if the publication is the last statement in the constructor. If the this reference escapes during construction, the object is considered not properly constructed.[8]

[8] More specifically, the this reference should not escape from the thread until after the constructor returns. The this reference can be stored somewhere by the constructor so long as it is not used by another thread until after construction. SafeListener in Listing 3.8 uses this technique.

Do not allow the this reference to escape during construction.

How would someone code against this to get to the OuterClass before it's finished constructing? What is the hidden inner class reference mentioned in italics in the first paragraph?

解决方案

Please see this article. There it's clearly explained what could happen when you let this escape.

And here is a follow-up with further explanations.

It's Heinz Kabutz amazing newsletter, where this and other very interesting topics are discussed. I highly recommend it.

Here is the sample taken from the links, which show how the this reference escapes:

public class ThisEscape {
  private final int num;

  public ThisEscape(EventSource source) {
    source.registerListener(
        new EventListener() {
          public void onEvent(Event e) {
            doSomething(e);
          }
        });
    num = 42;
  }

  private void doSomething(Event e) {
    if (num != 42) {
      System.out.println("Race condition detected at " +
          new Date());
    }
  }
}

When it gets compiled, javac generates two classes. The outer class looks like this:

public class ThisEscape {
  private final int num;

  public ThisEscape(EventSource source) {
    source.registerListener(new ThisEscape$1(this));
    num = 42;
  }

  private void doSomething(Event e) {
    if (num != 42)
      System.out.println(
          "Race condition detected at " + new Date());
  }

  static void access$000(ThisEscape _this, Event event) {
    _this.doSomething(event);
  }
}

Next we have the anonymous inner class:

class ThisEscape$1 implements EventListener {
  final ThisEscape this$0;

  ThisEscape$1(ThisEscape thisescape) {
    this$0 = thisescape;
    super();
  }

  public void onEvent(Event e) {
    ThisEscape.access$000(this$0, e);
  }
}

Here the anonymous inner class created in the constructor of the outer class is converted to a package-access class that receives a reference to the outer class (the one that is allowing this to escape). For the inner class to have access to the attributes and methods of the outer class, a static package-access method is created in the outer class. This is access$000.

Those two articles show both how the actual escaping occurs and what might happen.

The 'what' is basically a race condition that could lead to a NullPointerException or any other exception when attempting to use the object while not yet fully initialized. In the example, if a thread is quick enough, it could happen that it runs the doSomething() method while num has not yet been correctly initialized to 42. In the first link there's a test that shows exactly that.

EDIT: A few lines regarding how to code against this issue/feature were missing. I can only think about sticking to a (maybe incomplete) set of rules/principles to avoid this problem and others alike:

  • Only call private methods from within the constructor
  • If you like adrenaline and want to call protected methods from within the constructor, do it, but declare these methods as final, so that they cannot be overriden by subclasses
  • Never create inner classes in the constructor, either anonymous, local, static or non-static
  • In the constructor, don't pass this directly as an argument to anything
  • Avoid any transitive combination of the rules above, i.e. don't create an anonymous inner class in a private or protected final method that is invoked from within the constructor
  • Use the constructor to just construct an instance of the class, and let it only initialize attributes of the class, either with default values or with provided arguments

If you need to do further things, use either the builder or the factory pattern.

这篇关于如何通过发布内部类实例引用外部类转义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆