Static members are collected by GC when no longer needed?

Asked

Viewed 127 times

8

In a class that has a static variable, it exists throughout the application. The linked object is collected at some point?

Example:

public class Exemplo {
    private static List<int> lista = new List<int>();
}

1 answer

12


The variable will never be collected, it stays in a static area and as you said yourself, lasts the time of the application. So any object referenced by it will stay alive at all times. The static object is one of the GC research roots, so it will take a reference and keep the object alive.

But obviously it exists as the variable ceases to reference that variable. At some point the application can change the reference to another reference and then if the previously referenced object has no other references it will be collected.

Of course, if you undo this variable you also no longer have this reference.

If there is still a reference to the object it is possible to sign it for that static field again. If you no longer have references to it you cannot use the object again. The resurrection can only occur during his completion, which should be avoided. But this is another matter.

public class Exemplo {
    private static List<int> lista = new List<int>();
    public static TrocaLista() {
        lista = new List<int>(); //o objeto anterior ficará sem referência
    }
}

I put in the Github for future reference.

Actually if the variable has the attribute ThreadStatic the variable itself can be collected after the end of the thread.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.