我在正常情况下理解此警告,例如:
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/