reference - Can Java garbage collect variables before end of scope? -


suppose have program this:

void main() {     // point 0     bigthing bt = new bigthing();     // point 1     weakreference<bigthing> weak = new weakreference<>(bt);     // point 2     dosomething(weak);     // point 3 }  void dosomething(...) { ... } 

we know weak reference bigthing object cannot prevent object being garbage collected when becomes no longer reachable.

my question local variable bt strong reference bigthing object. does object become not-strongly-reachable @ point 2 (just before calling dosomething()) or @ point 3 (end of block scope)?

the answer question affect whether call dosomething() guaranteed able access live bigthing object, or whether underlying object can die during function call.

i uncertain because argue after point 2, local variable bt never read or written anymore, variable dead , pointer value can discarded. "optimization" valid if references strong, reasoning falls apart when notions of soft, weak, , phantom references introduced, , finalizers well. analogy, because c++ has destructors, value must destructed @ end of scope, , cannot moved ahead point of last usage.

i object collectable @ point 2, going following language in jls section 12.6.1:

optimizing transformations of program can designed reduce number of objects reachable less naively considered reachable. example, a java compiler or code generator may choose set variable or parameter no longer used null cause storage such object potentially reclaimable sooner.

since bt variable no longer used after point 2, java free clear variable, rendering bigthing object weakly reachable.


Comments