JHarnach
JHarnach

Reputation: 4034

Improving GC by deferencing objects

Concerning the efficiency of Garbage Collection: Is there any benefit to deliberately deferencing an object vs letting it fall out of scope ? Will the JVM actually do anything differently if I specifically set an Object to null ?

Expanding on that idea, is cleaning up Soft and/or Phantom references an effort worth making for the sake of improving GC-related performance ? I'm guessing code full of phantom references indicates a problem bigger than GC could solve of course.

Upvotes: 1

Views: 126

Answers (3)

nsfyn55
nsfyn55

Reputation: 15363

Most objects that you'd explicitly dereference will fall out of scope at the end of a given method call. However before this even became an issue the compiler would probably perform an escape analysis and decompose it into primatives. The net out is don't try to be smarter than the compiler or the garbage collector. Just take comfort that hotspot has deemed us too primative to pose a threat.

Upvotes: 0

João Fernandes
João Fernandes

Reputation: 1101

First, you may end up coding code (without noticing) that will keep creating objects that will never get out of scope but that are garbage for you at a certain point. Always keep an eye on this because it happens more frequently than many think.

Helping the GC is probably always a good practice although it may not produce significant results. However, thinking about the away a generational GC works, theory says that helping the GC should matter, as it is more expensive to remove old objects than new ones.

Upvotes: 1

user541686
user541686

Reputation: 210445

Only if you try to allocate something between when it's dereferenced and falls out of scope.

Unless the object is large (or holds the only indirect reference to lots of data), this isn't very useful.

Upvotes: 2

Related Questions