public void method()
{
{
String str = new String("value");
} // Line 1
} // Line 2
When is the earliest that the str object can be garbage collected? Would it be after it falls out of scope within the nested blocks [ Line 1 ] or would it be after the method completes [ Line 2 ]. I don’t know if objects that are on the stack ( within a method call ) can be garbage collected or if they are unable to be garbage collected until the stack is returned ( the method completes ). Or maybe I am making this too hard
when its garbage collected no body nows, however you can know when its eligable for garbage collection, if it was another Object i would tell you that it gets eligable for garbage collection when it gets out of scope. however this is a String then i think it will not be garbage collected and it will be inserted in the String pool.
You have mentioned a String object, so we got a SCP here. But again you have made an object by using the new statement, rather than the String Literal. Hence we can say it gets gc after line 1.
Just to organize what some of the other ranchers said:
1. An object is eligible for garbage collection when no active thread (in this case let's assume the only thread is the thread executing your method, the main thread) has an active reference (a reference which is accessible from your code) pointing to that object. So, in your case, the object becomes eligible for garbage collection after the reference str stops being an active reference. That happens when the code exits the block where str is declared. Line //1 closes the code block where str is declared, so after line //1 executes, you can say that one of the the String objects created (potentially, 2 objects were created, but the other one will be referenced from the String Constant Pool) is eligible for garbage collection. But that doesn't mean it will be garbage collected, as there are no guarantees on that.
2. Like Ravikanth said, objects are always created in the heap. Variables are another story (instance variables reside in the heap with the objects they belong to, as do static variables, whereas local references reside in the stack of the method they are declared in.)
Yes, you are right Omar. I think that String objects which a referred to from references in the SCP can never be garbage collected, although there might be an advanced way to do that which I am unaware of. Nothing to consider for the exam though, I am sure.
Post by:autobot
I'm doing laundry! Look how clean this tiny ad is:
a bit of art, as a gift, that will fit in a stocking