Java从堆中取消分配一个对象

发布于 2024-10-31 01:53:06 字数 324 浏览 1 评论 0原文

在 Java 中,要从堆中卸载对象,是否只需编写 myObject = null; 就足够了,GC 就会从那里处理它?

编辑:好吧,让我解释一下我的用例,因为每个人都假设我不应该显式地为 null 对象,所以我不应该担心它,等等。这没有抓住重点。我正在序列化一个对象,并在序列化它之前“消耗”该对象的一个​​字段,以节省磁盘空间。在你也对此表示同意之前,我不能声明这个字段transient,因为我有时会在对象中包含这个字段,但其他时候不会。

将对象设置为 null 对 GC 有影响吗?

In Java, to unload an object from the heap, is it sufficient to simply write myObject = null; and the GC will take care of it from there?

EDIT : Ok let me explain my use case, since everyone is assuming that I shouldn't explicitly null objects, I shouldn't worry about it, etc. That's missing the point. I am serializing an object, and am "consuming" a field of this object before I serialize it in order to save disk space. And before you jump down my throat for this, too, I cannot declare this field transient because I am including this field in the object sometimes, but not others.

Does setting an object to null have any effect on the GC?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

深居我梦 2024-11-07 01:53:06

在某些现代虚拟机中,主动将引用设置为 null 会阻碍垃圾收集器。你应该忘记这一点。

要了解对象何时被垃圾回收,请查看 java.lang.ref 包 - 尽管我可以诚实地说,在 16 年的 Java 编程生涯中,我从来不需要知道对象何时被回收垃圾收集。

您能详细说明为什么您认为您需要这个吗?

In some modern VMs, actively setting a reference to null hinders the garbage collector. You should just forget about that.

For knowing when an object is garbage collected, look at the java.lang.ref package - although I can honestly say that in 16 years of Java programming, I've never needed to know when an object is garbage collected.

Can you elaborate on why you think you need this?

十年不长 2024-11-07 01:53:06

不; 所有对该对象的引用都必须丢失/无效。实际上,这是您不应该担心的事情。

当不再使用您的对象时,它将被取消分配。请注意,保留给该对象的任何引用都会将该对象保留在堆上,并且简单地将 null 分配给任何单个引用不会导致底层对象神奇地消失。

No; all references to that object must be lost/nulled. In practice this is something you shouldn't worry about.

Your object will be de-allocated when it is no longer used. Just be aware that any references left to the object will keep the object on the heap and simply assigning null to any single reference will not cause the underlying object to magically go away.

相思碎 2024-11-07 01:53:06

不,也不。 myObject = null; 仅当没有对该对象的其他引用时才会有帮助,并且在大多数情况下这是多余的,因为本地对象在每个方法末尾都会超出范围。

至于对象何时真正被释放,完全取决于 GC。您可以做的是添加一个 finalize 方法 ,该方法将在对象之前调用被释放,但这也有问题,不应该依赖。

No, and no. myObject = null; will only help if there are no other references to the object, and in most cases it's superfluous because local objects go out of scope at the end of each method.

As for when objects are actually deallocated, that's completely up to the GC. What you can do is add a finalize method that will be called just before the object is deallocated, but this is problematic as well and should not be relied on.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文