How to make object in List eligible for garbage collection?

只愿长相守 提交于 2020-01-03 20:02:40

问题


I understand that when an object is added to a List, the List retains a reference to that object based on answer from this question Is this java Object eligible for garbage collection in List

How then how do you make the object in the List eligible for garbage collection so that it's removed from the heap and not taking up memory?

I ask because in JavaFX, a Vboxs getChildren method returns observable list containing the children nodes of the vbox. If a UI element is removed but not eligible for garbage collection, will this object still be on the heap consuming memory?


回答1:


Removing the references from that should make them subject of garbage collection (as long as no other object keeps references!).

You know, that is the whole idea how a GC works: it keeps those objects that are alive (can be reached from your initial starting point). Everything else is garbage; and subject to disposal once the GC decides to collect that garbage. And just to be precise here: you have to understand that these are two different activities. There might be a long time between object X "turns into garbage"; and "X gets collected; and memory is freed up".

One can use WeakReferences to avoid this; but of course, that requires that some piece of code would be pushing such WeakReference objects into the list initially. So, if you "own" this code, you could change that. But of course: that means that you always have to check if the object behind the WeakReference is still there when accessing the WeakReference.




回答2:


How then how do you make the object in the List eligible for garbage collection so that it's removed from the heap and not taking up memory?

Assuming that those objects are only referenced by this List, simply use the clear method

If a UI element is removed but not eligible for garbage collection, will this object still be on the heap consuming memory?

As long as an object is been hard referenced by at least one another object that is not itself eligible for garbage collection, the objet will be itself not eligible for garbage collection so it won't be collected by the GC it will then remain in the heap.




回答3:


If you cannot remove the object from the List, the only way I can think about to handle this would be wrapping your Objects into a WeakReference.



来源:https://stackoverflow.com/questions/38765109/how-to-make-object-in-list-eligible-for-garbage-collection

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