对象引用何时会被垃圾回收?

发布于 2024-12-25 21:03:09 字数 106 浏览 3 评论 0原文

有人告诉我,只有当引用设置为 null 时,垃圾收集器才会收集它。但是我认为垃圾收集器将收集所有超出范围的引用,这些引用从未被设置为空。

任何人都可以告诉我垃圾收集器何时会声明引用?

Someone told me only when a reference be set as null, the garbage collector will collect it. However I think the garbage collector will collect all out of scope references, which have never been set as null.

Anyone can told me when a reference will be claimed by the garbage collector?

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

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

发布评论

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

评论(3

苏璃陌 2025-01-01 21:03:09

GC 收集对象,而不是引用。

GC 将在对象不再有活动引用后的某个时间收集该对象。 (GC 是不确定的)

The GC collects objects, not references.

The GC will collect an object some time after it has no more live references. (the GC is non-deterministic)

少女的英雄梦 2025-01-01 21:03:09

某人的意思可能是,通过将保存该对象引用的变量设置为null,可以让 GC 在对象超出范围之前收集该对象。这种技术过去对于一些非常罕见的情况很有价值(例如,在不引用对象的长时间运行的循环之前)。如今的编译器技术使这个想法几乎毫无用处,因为编译器足够聪明,可以检测这些条件并采取相应的行动。

What that someone probably meant was that you can let GC collect an object before it goes out of scope by setting the variable that holds a reference to that object to null. This technique has been of value in the past for some very rare cases (for example, before a long-running loop that does not reference an object). The compiler technology these days renders this idea virtually useless, because compilers are smart enough to detect these conditions, and act accordingly.

你又不是我 2025-01-01 21:03:09

GC 会“在需要时”从内存中删除对象。您可以尝试运行 System.gc(),但这只是 GC 应该运行的提示。当 GC 运行时,它会查找未引用的对象(或仅具有弱引用的对象等)。 GC 运行频率取决于内存空间。它最常在 eden 空间中运行。默认情况下,GC 在 eden 空间满时运行,但您可以调整 JVM。

你为什么要打扰 GC?你有什么问题吗?

GC will removes an object from memory "when it wants". You can try to run System.gc() but it's just a hint for GC that it should run. Whne GC runs, it finds non-referenced objects (or objects with weak references etc. only). GC runs frequency depdens on memory space. It runs most often in eden space. By default GC runs in eden space when it gets full, but you can tune up your JVM.

Why are you bothering GC in the first place? What's your problem?

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