Reputation: 9478
Is there any garbage collection in below code?
public static void main(String []args){
System.out.println("Hello World");
Vector v1 = new Vector();
Vector v2 = new Vector();
v1 = null;
Vector v3 = v1;
v1 = v2;
v1.addElement(v2);
}
I answered as Yes as object v3
no longer getting accessed in the code.
Upvotes: 1
Views: 78
Reputation: 26926
After the code v1 = null
the object previously referenced by variable v1
is candidate to be garbage collected.
In addition no Exception
is thrown before the end of the main so a garbage collection could happen.
Note that is not sure that the garbage collection is invoked and probably is not because the code will finish soon without necessity of garbage collection.
Here an explanation line by line of your code.
Vector v1 = new Vector(); // Creates a new Vector (I call it vFirst) and assign it to v1
Vector v2 = new Vector(); // Creates a new Vector (I call it vSecond) and assign it to v2
v1 = null; // Now vFirst is not referenced by any variable so is candidate to be gc
Vector v3 = v1; // Assign a null value to v3
v1 = v2; // Assign to v1 the vector vSecond
v1.addElement(v2); // Add to the vSecond the element vSecond
As you can see after v1 = null the first Vector created can be garbage collected. It does not means that is garbage collected, but that it could be garbage collected if the GC needs memory.
Upvotes: 2
Reputation: 64
No. v3 is just a candidate for GC. There is no explicit GC statement here and it cannot be =)
Upvotes: 0
Reputation: 7348
After you assign any object to null, the object becomes eligible for garbage collection. It doesn't necessarily imply that it will be garbage collected at that point of time.
So when v3 becomes null, it is definitely eligible for gc, but at what time it will be garbage collected is not certain.
Upvotes: 1
Reputation: 7792
Once you assigned v1 = null;
the original Vector assigned to v1 is no longer accessable and will be garbage collected. v3 is null to begin with and will not be GCed
Upvotes: 1
Reputation:
The reference v1
was set to null
, therefore the object that was referred by this reference will be collected by the garbage collector. However, you cannot control the collection itself, you may ask the JVM to initiate it but it might get rejected. It all depends on the requirement of heap memory at runtime.
Upvotes: 1