Java中不同引用类型的使用
我最近一直在研究 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
两个奇怪的想法:
恕我直言,在某些(罕见)情况下,弱引用可能更适合缓存,例如,您可能会弱引用值,一旦将它们从使用它们的结构中删除(即,它们变得非常不可访问),就不可能再次需要它们。此外,JVM 中存在一个关于软引用的严重 bug ,这可能会迫使您这样做。
Two strange ideas:
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.