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
Since there's effectively always a "reference" to the static object, it will never get garbage collected.
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.
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 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.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With