Reputation: 5975
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)?
Upvotes: 3
Views: 1272
Reputation: 1836
private static String sample
Will begin to exist when it's first referenced in your code (the class loader loads it) and will stay alive independent of the existing object references.
Upvotes: 2
Reputation: 66637
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
Upvotes: 3
Reputation: 1500065
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.
Upvotes: 4