Pedantic
Pedantic

Reputation: 1378

How static variable treated by gc

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.

Upvotes: 3

Views: 707

Answers (1)

Cowan
Cowan

Reputation: 37533

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.

Upvotes: 7

Related Questions