Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is unused object available for garbage collection when it's still visible in stack?

In the following example there are two functionally equivalent methods:

public class Question {

    public static String method1() {
        String s = new String("s1");
        // some operations on s1
        s = new String("s2");
        return s;
    }

    public static String method2() {
        final String s1 = new String("s1");
        // some operations on s1
        final String s2 = new String("s2");
        return s2;
    }
}

however in first(method1) of them string "s1" is clearly available for garbage collection before return statement. In second(method2) string "s1" is still reachable (though from code review prospective it's not used anymore).

My question is - is there anything in jvm spec which says that once variable is unused down the stack it could be available for garbage collection?

EDIT: Sometimes variables can refer to object like fully rendered image and that have impact on memory.

I'm asking because of practical considerations. I have large chunk of memory-greedy code in one method and thinking if I could help JVM (a bit) just by splitting this method into few small ones.

I really prefer code where no reassignment is done since it's easier to read and reason about.

UPDATE: per jls-12.6.1:

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

So it looks like it's possible for GC to claim object which still visible. I doubt, however that this optimisation is done during offline compilation (it would screw up debugging) and most likely will be done by JIT.

like image 644
Petro Semeniuk Avatar asked Nov 11 '13 00:11

Petro Semeniuk


1 Answers

No, because your code could conceivably retrieve it and do something with it, and the abstract JVM does not consider what code is coming ahead. However, a very, very, very clever optimizing JVM might analyze the code ahead and find that there is no way s1 could ever be referenced, and garbage collect it. You definitely can't count on this, though.

like image 173
tbodt Avatar answered Sep 21 '22 06:09

tbodt