如何使列表中的对象符合垃圾回收的条件? [英] How to make object in List eligible for garbage collection?

查看:248
本文介绍了如何使列表中的对象符合垃圾回收的条件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,当一个对象被添加到List时,List会根据这个问题的答案保留对该对象的引用
此java对象是否有资格在列表中进行垃圾回收

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?

我问,因为在JavaFX中, Vboxs getChildren方法返回包含vbox的子节点的可观察列表。如果删除了一个UI元素但不符合垃圾回收的条件,那么这个对象是否仍然在堆消耗内存上?

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!).

你知道,这就是GC的工作原理:保持那些活着的对象(可以从你的初始起点到达)。其他一切都是垃圾;一旦GC决定收集垃圾,可以处置。而且在这里要确切:您必须了解这些是两个不同的活动。对象X变成垃圾之间可能需要很长时间;并且X被收集;内存被释放。

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".

可以使用 WeakReferences 以避免这种情况;但是,当然,这需要一些代码将最初将这样的WeakReference对象推送到列表中。所以,如果你拥有这段代码,你可以改变它。但当然:这意味着在访问WeakReference时,您总是必须检查WeakReference后面的对象是否仍然存在。

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.

这篇关于如何使列表中的对象符合垃圾回收的条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆