Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java / Android Garbage Collection of Static private variables

Lets say I have a Fragment defined as such:

public class MyFragment extends Fragment {
   private static String sample = "";

   public static void setSample(String s) {
      sample = s;
   }
}

for the lifetime of the Application, will sample get garbage collected (whether or not any references to MyFragment exist - which shouldn't matter I think)?

like image 733
StackOverflowed Avatar asked Mar 12 '26 00:03

StackOverflowed


2 Answers

You're right that the number of instances of MyFragment don't matter.

The sample variable will effectively be a GC root for as long as the classloader that loaded MyFragment is alive.

It's important to note that variables are never garbage collected - objects are.

like image 166
Jon Skeet Avatar answered Mar 14 '26 13:03

Jon Skeet


As long as the class is not unloaded, sample variable will not be garbage collected.

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

like image 27
kosa Avatar answered Mar 14 '26 14:03

kosa



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!