WHe will decide that any object is eligible for garbage collection and what are the options that decide that?

When is any particular object eligible for garbage collection? And what are the parameters that are taken into account that decide this?

MyClass mc = new MyClass();
mc.myMethod(); //line1

mc=null; //line2

mc=new object(); //line3
mc.myMethod(); //line4

mc=null; //line5


In this case, if the mc object is eligible for garbage collection?


source to share

3 answers

This division is accepted by the garbage collector, the condition for the object being collected is based on the number of references to it. Therefore, if an object has no references, it becomes a candidate for a collection.

This does not mean that it is collected by hand, just a candidate for collection. A collection of objects is defined by the generations engine :

An object is considered garbage when it can no longer be reached from any pointer in the running program. The most basic garbage collection algorithms simply iterate over every available object. Any remaining objects are then considered garbage. The time taken for this approach is proportional to the number of live objects, which is prohibitive for large applications that support a lot of live data.

As far as your code is concerned, the object created in the first line MyClass mc = new MyClass();

becomes a candidate for collection immediately after the thirdmc=null; //line2

Following the same pattern, a new object created in line3

(I don't think this line does what you think: shouldn't this line be mc = new MyClass();

?) Becomes a candidate after line 5 is executed.

Note that even if you delete line2

, the first object will be elegant for the collection because it is no longer referenced.



As soon as there are no active threads referenced (directly or indirectly through things like static fields) there is more to an object instance, it is eligible for garbage collection.

In your case after you have excluded the only reference to your objects on lines 2 and 5 respectively (you have two objects in the end).

Of course, if it mc.myMethod()

has a weird side effect that the mc

live maintains (like storing it in a thread local or static variable) then it might not be the case.



Every object that does not have , points to it by a variable that is eligible for garbage collection.

When you do: mc = null; // string2

The first object you create becomes valid for the Garbage collection because the mc variable no longer points to it!

This line will not compile: mc = new object ();

You cannot create an object this way. What is the object ?



All Articles