在方法中本地创建的对象的垃圾收集

发布于 2025-01-13 16:36:29 字数 272 浏览 3 评论 0原文

我认为,如果一个对象是在方法内本地创建的,并且从未泄漏到外部,那么一旦该方法执行完成,该对象就有资格进行垃圾回收。

但我很困惑,因为我读到有 4 个 GC 根 - 其中一个是线程对象,所以我很困惑,是否只有当方法本地对象所在的线程获得垃圾回收时,方法本地对象才会有资格进行垃圾回收创建完成并且该线程的GC Root被取消?

另外,如果有人可以阐明方法本地对象如何链接到堆的堆栈区域。

请注意,我已经阅读过有关方法本地对象的 GC 的内容,但我没有得到清晰详细的答案,所以我提出了这个问题。

I think if an object gets created locally within a method and is never leaked outside then that object will be eligible for garbage collection as soon as that method executed is completed.

But I am confused because I read that there are 4 GC roots - and one of then is the thread object, so I am confused that is it the case that method local objects will become eligible for garbage collection only when the thread in which it got created is complete and the GC Root of that thread is taken off?

Also, if someone can throw some light on how method local objects are linked to stack area of the heap.

PLEASE NOTE that I have read about GC of method local objects but nowhere I got a clear and detailed answer so I raised this question.

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

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

发布评论

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

评论(2

梨涡 2025-01-20 16:36:29

将线程调用堆栈视为堆栈帧节点的双向链表。每个节点都引用给定方法的所有局部变量,而这些变量又引用任何活动对象。线程的GC根本质上是链表的头节点,垃圾收集跟踪仍然链接的节点,从而找到所有存活的对象。当方法返回时,链表的尾节点将被删除,因此 GC 无法再发现它。

实际上,调用堆栈并不是以这种方式实现的,但行为本质上是相同的。

Think of the thread call stack as a doubly linked list of stack frame nodes. Each node references all the local variables for a given method, and these in turn reference any live objects. The GC root for the thread is essentially the head node of the linked list, and garbage collection traces the nodes that are still linked, thus finding all live objects. When a method returns, the tail node of the linked list is removed, and thus it's not discoverable by GC anymore.

In practice, the call stack isn't implemented this way, but the behavior is essentially the same.

深陷 2025-01-20 16:36:29

方法本地对象一旦停止使用,就可以进行垃圾回收,无论该方法是否完成。

方法实际上与垃圾收集几乎无关。

Method local objects are eligible for garbage collection as soon as they stop being used, whether or not the method is finished.

Methods really have almost nothing to do with garbage collection.

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