3

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)?

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.