什么时候应该弱引用使用? [英] When should weak references be used?

查看:543
本文介绍了什么时候应该弱引用使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我在一张Java的code的附带在WeakReferences - 我从来没有见过他们部署虽然我遇到他们,他们介绍的时候。这是一件应常规使用或当一个只运行到内存的问题?如果是后者,他们能很容易地改装或做了code需要认真重构?平均Java(或C#)程序员通常可以忽略它们吗?

I recently came across a piece of Java code with WeakReferences - I had never seen them deployed although I'd come across them when they were introduced. Is this something that should be routinely used or only when one runs into memory problems? If the latter, can they be easily retrofitted or does the code need serious refactoring? Can the average Java (or C#) programmer generally ignore them?

修改可以任何伤害进行过分热情用WR的吗?

EDIT Can any damage be done by over-enthusiastic use of WRs?

推荐答案

弱引用都是关于垃圾收集。 A 标准的对象不会消失,直到所有对它的引用被切断,这意味着所有引用的各种对象必须把它都将被免职之前,垃圾收集会认为这是垃圾。

Weak references are all about garbage collection. A standard object will not "disappear" until all references to it are severed, this means all the references your various objects have to it have to be removed before garbage collection will consider it garbage.

通过弱引用仅仅因为你的对象被其他对象所引用并不一定意味着它不是垃圾。它仍然可以与GC拾起并从内存中移除。

With a weak reference just because your object is referenced by other objects doesn't necessarily mean it's not garbage. It can still get picked up by GC and get removed from memory.

一个例子:如果我有一系列Foo对象在我的应用程序可能需要使用一组以保持中央记录所有的Foo的我身边。但是,当我的应用程序的其他部分通过删除所有引用删除Foo对象,我不想剩下我参考设置保存到该对象,以保持它被垃圾收集!真的,我只是希望它从我的组中消失。在这里,你会使用的东西就像一个弱集(Java有一个WeakHashMap中)代替,它使用弱引用其成员,而不是强引用。

An example: If I have a bunch of Foo objects in my application I might want to use a Set to keep a central record of all the Foo's I have around. But, when other parts of my application remove a Foo object by deleting all references to it, I don't want the remaining reference my Set holds to that object to keep it from being garbage collected! Really I just want it to disappear from my set. This is where you'd use something like a Weak Set (Java has a WeakHashMap) instead, which uses weak references to its members instead of "strong" references.

如果当你想他们,那么你已经在你的簿记犯了一个错误你的对象不被垃圾收集,东西仍​​然抱着你忘了删除的参考。使用弱引用可以减轻这种记帐的痛苦,因为你不必担心他们保持一个对象活着,并取消垃圾收集,但你不知道的有无的使用它们。

If your objects aren't being garbage collected when you want them to then you've made an error in your book keeping, something's still holding a reference that you forgot to remove. Using weak references can ease the pain of such book keeping, since you don't have to worry about them keeping an object "alive" and un-garbage-collected, but you don't have to use them.

这篇关于什么时候应该弱引用使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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