Java Anonymous Object and Garbage collection part

2019-09-22 06:12发布

问题:

private Student student = new Student();

public Student getStudent(){
    return student;
}


public void function(){
   getStudent().setName("john");
}

public void function(){
   Student student_local = getStudent();
   student_local.setName("john");
}

Does GC behave differently for both of the snip?

I mean which case (CASE-1/CASE-2) is more GC efficient in terms of Time?

I simple word GC will be called for CASE-1 or not?

回答1:

Amit i've seen your other question, what matters is always only reachability, it doesn't matter how you use student, it will always be reachable until the class that contains it is reachable.

Update, regarding the question you added:

I mean which case (CASE-1/CASE-2) is more GC efficient in terms of Time?

Neither because you do the same thing in both functions and remember that you can't really know when your objects will be collected, and it doesn't even matter for this kind of examples.

Read this description of how GC works: http://www.cubrid.org/blog/dev-platform/understanding-java-garbage-collection/

Edited: Should learn to read the questions, read this revision of my answer, sorry Amit.



回答2:

In all the three cases method function() operates on an instance variable that was instantiated at the time of class initialization. That means that instance variable student will continue to hold a reference to the object Student after the method function completes in all cases and thus the object will not become a candidate for garbage collection. That also means that the efficiency of those code snippets in terms of garbage collection will be identical (since the GC will not collect the student object after the methods complete in all cases)