Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java object garbage collection

I am working on the OCA Java certification and unsure of how to understand the answer to one question.

public class Test {

public static void main(String[] args){
    Student s1 = new Student("o1"); 
    Student s2 = new Student("o2");
    Student s3 = new Student("o3");
    s1=s3; 
    s3=s2;
    s2=null;
    //HERE
    }
}

The question is which object will be available for garbage collection after the //HERE point.

The answer provided by the online test is : One object (o1).

Can someone explain me why?

like image 875
a1a1a1a1a1 Avatar asked Dec 14 '22 07:12

a1a1a1a1a1


2 Answers

Consider a simple class Student.

Step 1 :

Student s1 = new Student("s1"); 
Student s2 = new Student("s2");
Student s3 = new Student("s3");

s1, s2, s3 are referencing 3 object in the heap space

enter image description here

Step 2 :

Student s1 = s3; 

s1 is now referencing the s3 object in the heap space

the object s1 in the heap space has lost his reference

enter image description here

Step 3 :

Student s1 = s3;
Student s3 = s2;

Variable s1 reference s3 heap space

Variable s3 reference s2 heap space

enter image description here

Step 4 :

Student s1 = s3;
Student s3 = s2;
Student s2 = null;

Variable s1 reference s3 heap space

Variable s3 reference s2 heap space

Variable s2 lost his reference (null pointer)

enter image description here

Conclusion :

After line 11, one object is eligible for garbage collection

like image 190
Boris S. Avatar answered Jan 01 '23 05:01

Boris S.


Every time these kind of questions pop-up, the answer is still the same: after the comment HERE, every single object is eligible for garbage collection. Nothing is used after that line, thus no strong reference exist to any object, thus everything is eligible for GC. Unfortunately, these kind of questions make sense only in the context of getting the correct "points" for the exam, thus people learn them the way they are. The reality is that without a broader context of reachability, they only confuse users, imo.

Think about - are there are any live references to any of your objects after that comment? No. As such, is every single instance eligible for GC? yes. And note that they are eligible after that comment, not after the methods ends. Do not mash scope an reachability together.

like image 41
Eugene Avatar answered Jan 01 '23 03:01

Eugene