Assume the following code:
public void foo() { C c = new C(); bar(c.baz); // assume that baz does not reference c }
I was under the impression that HotSpot would not garbage collect c before the local variable went out of scope although it is legally allowed to do so. I even heard of issues where unnecessary garbage was retained as a result (usual workarounds are to null the variable or to inline it).
According to this bug report (Server JIT optimization can cause objects to go out of scope prematurely), the Server VM is actually able to GC the object before the local variable goes out of scope. It would be interesting to know if it can detect such cases reliably.
This topic sometimes confuses developers that are analyzing heap dumps as they expect particular locals to be reported as roots but they aren’t present in the dump. When a debugger agent is running then you will notice that are locals do appear to be in scope. This is necessary to allow the developer access them in the debugger.
You might be interested in the linked pdf on ‘Garbage Collection-Friendly Programming’, I’m thinking of slides 16 & 17. “Nulling references rarely helps the GC… The JIT can do liveness analysis…”
Thank you Alan, that’s useful to know.
Regarding the GC-Friendly Programming slides, I thought I had seen them before, but seems like I had missed the liveness analysis bit. Thank you for the link Iain.