Reputation: 11
In my sample code, which of my Test
objects will be eligible for garbage collection at the end of execution?
interface Animal1
{
void makeNoise();
}
class Horse implements Animal1
{
Long weight = 1200L;
@Override
public void makeNoise()
{
System.out.println("Whinny");
}
}
public class Test extends Horse
{
public void makeNoise()
{
System.out.println("wginny");
}
public static void main(String str[])
{
Test t1 = new Test();
Test t2 = new Test();
Test t3 = new Test();
t3 = t1;
t1 = t2;
t2 = null;
t3 = t1;
}
}
Upvotes: 1
Views: 77
Reputation: 5948
Not sure if this is what you're asking, but I count 6.
1: Test t1 original value
2: Test t2 original value
3: Test t3 original value
4: Long t1.weight (autoboxed. not flyweighted because of the high value)
5: Long t2.weight (autoboxed. not flyweighted because of the high value)
6: Long t3.weight (autoboxed. not flyweighted because of the high value)
Note that any methods called would only allocate 1 flyweighted string. Strings are immutable & Java would share these references.
Upvotes: 0
Reputation: 2012
Test t1=new Test();
Test t2=new Test();
Test t3=new Test();
t3=t1;
t1=t2;
t2=null;
t3=t1;
The answer would be t3 and t1. t2 still has a reference that is stored into t1, and then stored into t3. the original objects created for t1 and t3 are eligible for garbage collection as they no longer have strong references anymore since different values were saved to them. A good mental exercise, but this is probably homework that you just copy pasted anyways.
The longs are all eligible for garbage collection once strong references to their enclosing object disappear.
Alternatively, all of the objects are eligible for garbage collection if your application exits.
Upvotes: 1