Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Garbage collection of static members

Will static members be ever collected by the garbage collector?

like image 874
Bhaskar Avatar asked May 12 '09 06:05

Bhaskar


People also ask

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.

Which objects are garbage collected?

An object is eligible to be garbage collected if its reference variable is lost from the program during execution. Sometimes they are also called unreachable objects. What is reference of an object?

Which method is used for garbage collection?

The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc() is found in System and Runtime classes.

What is garbage collection explain?

Garbage collection (GC) is a memory recovery feature built into programming languages such as C# and Java. A GC-enabled programming language includes one or more garbage collectors (GC engines) that automatically free up memory space that has been allocated to objects no longer needed by the program.


2 Answers

Objects referenced by static variables will only be garbage collected when the relevant AppDomain is garbage collected. In client applications, there's often just a single AppDomain which lives for the duration of the process. (An exception is when the application uses a plug-in architecture - different plug-ins may be loaded in different AppDomains and the AppDomain may be unloaded later.)

In ASP.NET, "AppDomain recycling" happens periodically (for various reasons) - when this occurs, and the static variables within that AppDomain will no longer act as GC roots, and thus won't prevent objects being garbage collected.

If you were worried about an object being garbage collected while you still had a reference to it via a static variable, though, you can relax. While you can access the object, it won't be garbage collected.

like image 89
Jon Skeet Avatar answered Oct 20 '22 00:10

Jon Skeet


Members are not collected... Objects are.
So if you set the Ref. Type static member to null, any object it was previously pointing to would be collected. If not, it will hang around till the AppDomain goes down (Each AppDomain has its own set of static stuff)

like image 27
Gishu Avatar answered Oct 20 '22 00:10

Gishu