Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do static members ever get garbage collected?

Do static member variables ever get garbage collected?

For example, let's use the following class.

public class HasStatic {     private static List<string> shared = new List<string>();  } 

And supposed that it's used like this:

//Startup { HasStatic a = new HasStatic(); HasStatic b = new HasStatic(); HasStatic c = new HasStatic(); HasStatic d = new HasStatic(); //Something } //Other code //Things deep GC somewhere in here HasStatic e = new HasStatic(); 

When a, b, c, and d are garbage collected does the static member shared get collected as well? Could e possibly get a new instance of shared?

like image 556
C. Ross Avatar asked Jul 06 '11 16:07

C. Ross


People also ask

Do static methods get garbage collected?

No. Methods are not garbage collected because they don't exist in the heap in the first place.

Why static variables are not garbage collected?

Because static variables are referenced by the Class objects which are referenced by ClassLoaders. So, Static variables are only garbage collected when the class loader which has loaded the class in which static field is there is garbage collected in java.

When should you not use garbage collection?

Show activity on this post. The obvious cases for not using garbage collection are hard realtime, severely limited memory, and wanting to do bit twiddling with pointers.

Do threads get garbage collected?

The Thread is not garbage collected because there are references to the threads that you cannot see. For example, there are references in the runtime system. When the Thread is created it is added to the current thread group.


1 Answers

No, static members are associated with the Type, which is associated with the AppDomain it's loaded in.

Note that there doesn't have to be any instances of HasStatic for the class to be initialized and the shared variable to have a reference to a List<string>.

Unless you're considering situations where AppDomains get unloaded, static variables can be regarded as GC roots forever. (Of course, if something changes the value of HasStatic.shared to reference a different instance, the first instance may become eligible for garbage collection.)

like image 130
Jon Skeet Avatar answered Sep 27 '22 22:09

Jon Skeet