Is this java Object eligible for garbage collection in List

倾然丶 夕夏残阳落幕 提交于 2019-12-19 17:12:11

问题


What I am asking might be a stupid question so please pardon me for that. So it goes like this :

List<Boss> bossList = new ArrayList<Boss>();
Boss b = null;
for(Employee e : List<Employee> myList){
    b = new Boss();
    b.setEmployee(e);
    bossList.add(b);
    b = null;
}

So in above scenario, I am creating lot of Boss objects and then de-referencing them(I know I don't need to write "b = null", but i did it for clarity of my question). In normal scenario, I would have marked them to garbage collection, by doeing this, but because in this scenario, I am adding those Boss objects in List collection, are they marked for GC or not? If not then why? And how does List collection work internally to hold references for each Object added, so as to avoid garbage collection?

[EDIT] 

The scope of question is only limited to the individual Boss objects created in for loop, considering that this method returns the reference of the List to the outside world.


回答1:


ArrayList has Object[] elementData internally. When you added b to bossList ArrayList assigned elementData[0] = b. So when you assigned null to b the instance of Boss is still referenced from elementData[0] and cannot be GCed. But since ArrayList instance is referenced only from method's variable after the method returns both ArrayList and Boss instances will be eligible for GC.




回答2:


The Boss objects will not be collected by the GarbageCollector because they are still referenced in the code block that you are posted. bossList is an ArrayList which has an internal array of Object thus holding references to those objects which are added to it.

I such a situation not only the references by you are considered but all referneces in all objects involved.

EDIT: Since you are returning the List in your code the objects will not be marked for garbage collection until the list is no longer referenced in your program.




回答3:


Here's what really happens with your code :




回答4:


Since java is pass by reference, whenever you add b to bossList, bossList starts referencing the memory location which b is pointing to. So when b nullified only link from b to the reference is broken. Thus keeping the object accessible through bossList.



来源:https://stackoverflow.com/questions/16850413/is-this-java-object-eligible-for-garbage-collection-in-list

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