Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Java garbage collect variables before end of scope?

Suppose we have a program like 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 that the weak reference to the BigThing object cannot prevent the object from being garbage collected when it becomes no longer strongly reachable.

My question is about the local variable bt which is a strong reference to the BigThing object. Does the object become not-strongly-reachable at point 2 (just before calling doSomething()) or at point 3 (end of block scope)?

The answer to this question will affect whether the call to doSomething() is guaranteed to be able to access the live BigThing object, or whether the underlying object can die during the function call.

I am uncertain because you could argue that after point 2, the local variable bt is never read or written anymore, so the variable is effectively dead and the pointer value can be discarded. This "optimization" would be valid if all references were strong, but the reasoning falls apart when the notions of soft, weak, and phantom references are introduced, and finalizers as well. Also as an analogy, because C++ has destructors, a value must be destructed at the end of the scope, and cannot be moved ahead to the point of last usage.

like image 383
Nayuki Avatar asked Sep 02 '16 05:09

Nayuki


1 Answers

I would say the object is collectable at point 2, going by the following language in JLS section 12.6.1:

Optimizing transformations of a program can be designed that reduce the number of objects that are reachable to be less than those which would naively be considered reachable. For example, a Java compiler or code generator may choose to set a variable or parameter that will no longer be used to null to cause the storage for such an object to be potentially reclaimable sooner.

Since the bt variable will no longer be used after point 2, Java is free to clear that variable, rendering the BigThing object only weakly reachable.

like image 145
user2357112 supports Monica Avatar answered Oct 07 '22 02:10

user2357112 supports Monica