Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When will an object declared in a static class get garbage collected?

 public static class stClass
{
    static Class1 obj = new Class1();

    public static int returnSomething()
    {
        return 0;
    }
}

When will the Class1 instance obj in stClass get garbage collected, if i am calling the static function stClass.returnSomething() in some other non static class ?

Note: Class1 is not static

like image 989
Vamsi Avatar asked Mar 10 '11 07:03

Vamsi


People also ask

Do static classes get garbage collected?

Since there's effectively always a "reference" to the static object, it will never get garbage collected.

When an object becomes eligible for garbage collection?

An object is eligible for garbage collection when there are no more references to that object. References that are held in a variable are usually dropped when the variable goes out of scope. Or, you can explicitly drop an object reference by setting the variable to the special value null.

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.

What triggers garbage collection?

When a JVM runs out of space in the storage heap and is unable to allocate any more objects (an allocation failure), a garbage collection is triggered. The Garbage Collector cleans up objects in the storage heap that are no longer being referenced by applications and frees some of the space.


2 Answers

Never, as obj does not implement IDisposable.

If you mean when will obj get garbage collected then the answer is still never - static fields are never garbage collected and so the object that obj references will only become eligible for garbage collection if you set obj to be null (or some other object) and have no other references to that object:

obj = null;

(or if your app domain is unloaded / the process ended)

like image 174
Justin Avatar answered Oct 12 '22 01:10

Justin


It will never get disposed as it doesn't implement IDisposable. However it will get garbage collected. This will happen when you exit your application or you destroy the AppDomain that the class was created in.

like image 43
Can Gencer Avatar answered Oct 12 '22 02:10

Can Gencer