garbage collection - Can java finalize an object when it is still in scope? -



garbage collection - Can java finalize an object when it is still in scope? -

i've been looking bug in code seems caused "ugly" finalizer code. code looks this

public class { public b b = new b(); @override public void finalize() { b.close(); } } public class b { public void close() { /* clean our resources. */ } public void dosomething() { /* requires not closed */ } } void main() { a = new a(); b b = a.b; for(/*lots of time*/) { b.dosomething(); } }

what think happening a getting detected having no references after sec line of main() , getting gc'd , finalized finalizer thread - while for loop still happening, using b while a still "in scope".

is plausable? java allowed gc object before goes out of scope?

note: know doing within finalizers bad. code i've inherited , intending prepare - question whether i'm understanding root issue correctly. if impossible more subtle must root of bug.

can java finalize object when still in scope?

yes.

however, i'm beingness pedantic here. scope language concept determines validity of names. whether object can garbage collected (and hence finalized) depends on whether reachable.

the answer ajb had (+1) citing important passage jls. don't think it's straight applicable situation. jls §12.6.1 says:

a reachable object object can accessed in potential continuing computation live thread.

now consider applied next code:

class { @override protected void finalize() { system.out.println(this + " finalized!"); } public static void main(string[] args) { a = new a(); system.out.println("created " + a); (int = 0; < 1_000_000_000; i++) { if (i % 1_000_000 == 0) system.gc(); } // system.out.println(a + " still alive."); } }

on jdk 8 ga, finalize a every single time. if uncomment println @ end, a never finalized.

with println commented out, 1 can see how reachability rule applies. when code reaches loop, there no possible way thread can have access a. unreachable , hence subject finalization , garbage collection.

note name a still in scope because 1 can utilize a anywhere within enclosing block -- in case main method body -- declaration end of block. exact scope rules covered in jls §6.3. really, can see, scope has nil reachability or garbage collection.

to prevent object beingness garbage collected, can store reference in static field, or if don't want that, can maintain reachable using later on in same method after time-consuming loop. should sufficient phone call innocuous method tostring on it.

java garbage-collection

Comments

Popular posts from this blog

model view controller - MVC Rails Planning -

ruby on rails - Devise Logout Error in RoR -

html - Submenu setup with jquery and effect 'fold' -