何时在Java中使用Weak和Phantom引用 [英] When to use Weak and Phantom references in Java

查看:140
本文介绍了何时在Java中使用Weak和Phantom引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读了很多文章,但我不明白 - 在实践中我需要在哪里使用Weak和Phantom参考?软引用 - 正如我所理解的那样,是缓存的不错选择。但弱和幻影,我不知道何时使用。请提供我们需要使用它们的实际任务示例。

I read many articles, but I don't understand - where do I need to use Weak and Phantom references in practice? Soft references - is a good choice for cache, as I understand. But weak and phantom, I don't know when to use. Please provide examples of real tasks where we need to use them.

推荐答案

您可以使用弱引用进行缓存,就像软引用一样如你所说。

You can use weak references for cache, simply like soft references as you said.

PhantomReferences有什么用?我只知道它们有两个严重的情况:首先,它们允许您确定从内存中删除对象的确切时间。事实上,它们是确定这一点的唯一方法。这通常不是很有用,但在某些非常具体的情况下可能会派上用场,例如操作大图像:如果你确定图像应该被垃圾收集,你可以等到它实际上是在尝试加载下一个图像之前,因此使可怕的OutOfMemoryError不太可能。

What good are PhantomReferences? I'm only aware of two serious cases for them: first, they allow you to determine exactly when an object was removed from memory. They are in fact the only way to determine that. This isn't generally that useful, but might come in handy in certain very specific circumstances like manipulating large images: if you know for sure that an image should be garbage collected, you can wait until it actually is before attempting to load the next image, and therefore make the dreaded OutOfMemoryError less likely.

其次,PhantomReferences避免了最终化的基本问题:f​​inalize()方法可以通过创建新的强引用来复活对象他们。那么,你说什么?好吧,问题是现在必须确定覆盖finalize()的对象至少在两个单独的垃圾收集周期中是垃圾才能被收集。当第一个周期确定它是垃圾时,它就有资格完成。由于在完成期间对象被复活的(微小但不幸的是真实的)可能性,垃圾收集器必须在实际移除对象之前再次运行。并且由于最终确定可能没有及时发生,因此在对象等待最终确定时可能会发生任意数量的垃圾收集周期。这可能意味着实际清理垃圾对象的严重延迟,这就是为什么即使大部分堆都是垃圾也可以获得OutOfMemoryErrors。

Second, PhantomReferences avoid a fundamental problem with finalization: finalize() methods can "resurrect" objects by creating new strong references to them. So what, you say? Well, the problem is that an object which overrides finalize() must now be determined to be garbage in at least two separate garbage collection cycles in order to be collected. When the first cycle determines that it is garbage, it becomes eligible for finalization. Because of the (slim, but unfortunately real) possibility that the object was "resurrected" during finalization, the garbage collector has to run again before the object can actually be removed. And because finalization might not have happened in a timely fashion, an arbitrary number of garbage collection cycles might have happened while the object was waiting for finalization. This can mean serious delays in actually cleaning up garbage objects, and is why you can get OutOfMemoryErrors even when most of the heap is garbage.

有关详细信息,请参阅此页面:
http://weblogs.java.net/blog / 2006/05/04 /理解 - 弱参考

for more details see this page : http://weblogs.java.net/blog/2006/05/04/understanding-weak-references

这篇关于何时在Java中使用Weak和Phantom引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆