How do you make the item eligible for garbage collection?

advertisements

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?


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.