Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 589
Pedantic Avatar asked Dec 03 '25 17:12

Pedantic


1 Answers

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.

like image 107
Cowan Avatar answered Dec 06 '25 07:12

Cowan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!