Christ
Christ

Reputation: 155

When do static variables get garbage collected?

I have a static factory method which will return a fragment object.

private static String  final A1="a1";
private static String  final A2="a2";
private static String  final A3="a2";
private static String  final A4="a4";

public static MyFragment newInstance(int index) {
    MyFragment f = new MyFragment();
    Bundle args = new Bundle(4);
    args.putInt(A1, index);
    args.putInt(A2, index);
    args.putInt(A3, index);
    args.putInt(A4, index);
    f.setArguments(args);
    return f;
}

And am getting it within oncreate()

getArguments().getInt(A1, 0);

Now my question is: I am creating couple of MyFragment object like below

List<Fragment> fragments = new ArrayList<>();
fragments.add(MyFragment.newInstance(defaultId));
int i = 1;
for (Categories categories : mCategories) {
    String id = categories.getCategory_id();
    String name = categories.getCategory_name();
    //  String slno = categories.getSlno();
    fragments.add(MyFragment.newInstance(defaultId));
    Titles[i] = name;
    i++;
}

As the variables A1-A4 as static will it clear it's memory on activity destroy ? or i need to assign the variables as null in onDistroy ?

Please help me to clarify the doubt ?

Upvotes: 3

Views: 3537

Answers (1)

James Wierzba
James Wierzba

Reputation: 17508

A static variable is allocated when the class is loaded, and it will only be garbage collected if the class loader that loaded the class is itself deallocated.

A class or interface may be unloaded if and only if its defining class loader may be reclaimed by the garbage collector [...] Classes and interfaces loaded by the bootstrap loader may not be unloaded.

See the answer to a similar question Are static fields open for garbage collection?

Upvotes: 2

Related Questions