java - 构造函数调用可覆盖方法(延迟调用)

标签 java constructor callback overriding

我在正常情况下理解此警告,例如:

class Test {
  public Test() {
    hello();
  }
  public void hello() {}
}

但是如果我们有类似的东西怎么办:

class Test {
  public Test() { 
    // Put the call on a queue that will be executed later
    queue.submit( new Runnable() { 
      public void run() {
        hello();
      }
    });
  }
  public void hello() {}
}

对 hello() 的调用不会立即发生。即使在子类准备好构造很久之后回调执行的情况下,这仍然是不好的/有风险的吗?

最佳答案

Is this still bad/risky even in the case where the callback executes long after the subclass is ready constructed

是的,它仍然有风险。构造函数调用不是原子的,因此如果您在另一个线程中延迟从构造函数调用实例方法同样安全,因为您无法保证在线程(最终)被调用。

现在,假设,如果子类对象完全构造(强调 if),那么是的, future 的回调将是安全的。换句话说,它不会绕过部分构建的对象,这比访问它更危险。

关于java - 构造函数调用可覆盖方法(延迟调用),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16146689/

相关文章:

java - 从一行中获取特定单词

java - 应用程序没有响应

java - Java 中的信号量和线程池

c++ - 如何区分参数为非嵌套和嵌套 initializer_list 的两个重载函数?

c++ - LNK2019 在 Qtcreator 上实例化对象 c++ 时

javascript - 如何摆脱 JavaScript 中的绑定(bind)情况

java - 如何在不将 List 包装在其他类中的情况下验证 spring Controller 参数中 List 中的每个对象?

c++ - 如何在 C++ 中围绕异步回调创建同步包装器?

c# - 将字符串作为参数从 C# 传递到 C++ 中的回调函数

java - 使用 "this"和 "super"调用构造函数