Is this Java object available for garbage collection in a list

What I ask may be a stupid question, so please forgive me for that. So this happens as follows:

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 the above scenario, I create a lot of Boss objects and then de-link to them (I know that I do not need to write "b = null", but I did this to clarify my question). In a normal scenario, I would mark their garbage collection by doing this, but since in this scenario I add those Boss objects to the List collection, are they marked for GC or not? If not, why? And how does the List collection work internally to contain links for each added object to avoid garbage collection?

 [EDIT] 

The scope of the question is limited only to individual Boss objects created in the for loop, given that this method returns a list link to the outside world.

+7
source share
4 answers

ArrayList has an Object[] elementData internally. When you added b to bossList ArrayList, assigned elementData[0] = b . Therefore, when you assigned null to b , the Boss instance still refers to elementData[0] and cannot be GCed. But since an ArrayList instance only refers to a method variable after the method returns ArrayList and Boss instances, it will be eligible for GC.

+5
source

Boss objects will not be collected by GarbageCollector because they are still referenced in the code block that you publish. bossList is an ArrayList that has an internal array of Object , thereby preserving references to those objects that are added to it.

In such a situation, not only your links are considered, but also all the links in all the objects involved.

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

+10
source

Here is what really happens with your code:

Hello

+3
source

Since java is passed by reference, whenever you add b to bossList , bossList starts to reference the memory location pointed to by b. Therefore, when b reset only the link from b to the link is violated. Thus, keeping the object accessible through bossList .

-one
source

All Articles