Java中不同引用类型的使用

发布于 2024-10-14 02:34:38 字数 368 浏览 2 评论 0原文

我最近一直在研究 Java 中的软引用类型、弱引用类型和幻像引用类型,并且想知道它们是否有任何我没有遇到过的用途。我过去曾将它们用于各种用途,并且它们总是属于以下类别:

  • 使用幻像引用代替终结器 - 我更喜欢这样做,因为死对象复活的机会为 0
  • 在 a 中使用弱引用 例如其源无法修改)
  • hashmap 来保存 object=>value 映射,只有当对象存在于其他地方时,映射才应到位(当需要向库中的对象添加额外信息时有用, 用于缓存的引用(比弱引用效果好得多,因为 JVM 将它们保留更长时间,并且只有在认为需要时才会释放它们。)

但是,那里只有 3 个用途,而且我敢说它们可能还有更多用处我从来没有遇到过。欢迎所有建议!

I've recently been playing around with soft, weak and phantom reference types in Java and have been wondering if there's any uses out there for them that I haven't come across. I've used them in the past for various things and they've always fallen under the category of the following:

  • Using phantom references in place of finalizers - I prefer this since there's 0 chance of a dead object being resurrected
  • Using weak references in a hashmap to hold an object=>value mapping, where the mapping should only be in place if an object exists elsewhere (useful when needing to add extra information to an object in a library for instance whose source can't be modified)
  • Using soft references for caching (works much better than weak references because the JVM keeps them around for much longer and only lets go if it feels it needs to.)

However, there's only 3 uses there and I daresay there's lots more things that they might be useful for which I've never come across. All suggestions welcome!

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

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

发布评论

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

评论(1

眼趣 2024-10-21 02:34:38

两个奇怪的想法:

  • 您可以使用软引用来发现内存不足,并手动释放一些本身无法使用软引用的缓存。
  • 您可以使用弱引用来查明 GC 何时运行,这在您遇到奇怪的程序暂停(可能与 GC 相关或无关)时可能很有用。

恕我直言,在某些(罕见)情况下,弱引用可能更适合缓存,例如,您可能会弱引用值,一旦将它们从使用它们的结构中删除(即,它们变得非常不可访问),就不可能再次需要它们。此外,JVM 中存在一个关于软引用的严重 bug ,这可能会迫使您这样做。

Two strange ideas:

  • You may use a soft reference for finding out you're low on memory and manually freeing some caches which themselves can't use soft references.
  • You may use a weak reference to find out when the GC runs, which may be useful in case you're experiencing strange program pauses which may or may not be related to the GC.

IMHO, in some (rare) cases weak references may be better for caching, e.g., you may weakly refer to values, which are improbable to be needed again once they get removed from the structures using them (i.e., they get strongly unreachable). Moreover, there's a serious bug in the JVM concerning soft references, which may force you to do so.

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