Java Anonymous Object and Garbage collection part -2

廉价感情. 提交于 2019-12-13 10:02:23

问题


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)



来源:https://stackoverflow.com/questions/29081859/java-anonymous-object-and-garbage-collection-part-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!