I've been looking into a bug in my code that seems to be caused by some "ugly" finalizer code. The code looks roughly like this
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();
   }
}
What I think is happening is that a is getting detected as having no references after the second line of main() and getting GC'd and finalized by the finalizer thread - while the for loop is still happening, using b while a is still "in scope".
Is this plausable? Is java allowed to GC an object before it goes out of scope?
Note: I know that doing anything inside finalizers is bad. This is code I've inherited and am intending to fix - the question is whether I'm understanding the root issue correctly. If this is impossible then something more subtle must be the root of my bug.
 
     
     
    