views:

63

answers:

1

How are static variable treated by the garbage collector and where are they allocated memory? on the heap or stack (as member variables) Please clarify this for me.

+6  A: 

Static variables are only eligible for garbage collection when the class itself is garbage collected -- and classes are only eligible for garbage collection if the classloader which loaded them is garbage collected.

See JLS § 12.7:

A class or interface may be unloaded if and only if its defining class loader may be reclaimed by the garbage collector as discussed in §12.6. Classes and interfaces loaded by the bootstrap loader may not be unloaded.

Static fields are allocated on the heap.

Cowan