WeakHashMap - 它的目的是什么以及如何正确使用它
今天我发现这篇博文讨论了用法缓存上的 WeakHashMap
。令人感兴趣的是,键不是值而是被存储为弱引用,当引用不再有效时,整个键值对就会从 WeakHashMap 中删除。因此,这将导致发生以下情况:
WeakHashMap map = new WeakHashMap();
SomeClass myReference1 = ....
map.put(new Long(10), myReference1);
// do some stuff, but keep the myReference1 variable around!
SomeClass myReference2 = map.get(new Long(10)); // query the cache
if (myReference2 == null) {
// this is likely to happen because the reference to the first new Long(10) object
// might have been garbage-collected at this point
}
我很好奇什么情况下会利用 WeakHashMap
类?
Today I found this blog post which discussed usages of WeakHashMap
over cache. It was intrigued by the fact that not the values, but the keys are stored as weak references, and when the reference is no more alive, the entire key-value pair is removed from the WeakHashMap. This would therefore cause the following to happen:
WeakHashMap map = new WeakHashMap();
SomeClass myReference1 = ....
map.put(new Long(10), myReference1);
// do some stuff, but keep the myReference1 variable around!
SomeClass myReference2 = map.get(new Long(10)); // query the cache
if (myReference2 == null) {
// this is likely to happen because the reference to the first new Long(10) object
// might have been garbage-collected at this point
}
I am curious what scenarios then would take advantage of the WeakHashMap
class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当您想要将元数据附加到您无法控制其生命周期的对象时。一个常见的例子是类加载器,但必须注意避免创建值->键引用循环。
When you want to attach metadata to an object for which you don't control the lifecycle. A common example is ClassLoader, though care must be taken to avoid creating a value->key reference cycle.
有很多用途,但一个真正重要的用途是当您想通过
Class
键入某些内容时。维护对 Class 实例的强引用可以固定整个类加载器。顺便说一句,Guava 有一套更完整的非强引用映射结构。
There are many uses, but one really important one is when you want to key something by
Class
. Maintaining a strong reference toClass
instances can peg entire classloaders.As an aside, Guava has a much more complete set of non-strong reference mapping constructs.
我运行示例代码来了解 HashMap 和 WeakHashMap 之间的区别,希望它有所帮助
输出将是:
I ran the sample code to understand the difference between HashMap and WeakHashMap, Hope it helps
The output will be: