我一直在研究我的代码中的一个错误,这个错误似乎是由一些"丑陋的"终结器代码引起的.代码看起来大致如此
public class A {
public B b = new B();
@Override public void finalize() {
b.close();
}
}
public class B {
public void close() { /* do clean up our resources. */ }
public void doSomething() { /* do something that requires us not to be closed */ }
}
void main() {
A a = new A();
B b = a.b;
for(/*lots of time*/) {
b.doSomething();
}
}
Run Code Online (Sandbox Code Playgroud)
我认为正在发生的事情是,a在第二行之后检测到没有引用main()并获得GC并最终确定终结器线程 - 当for循环仍然发生时,使用 …