有人可以向我解释使用MapMaker或WeakHashMaps何时有用吗? [英] Can someone explain to me when it is useful to use MapMaker or WeakHashMaps?

查看:183
本文介绍了有人可以向我解释使用MapMaker或WeakHashMaps何时有用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了许多非常喜欢

I have read many people really like the MapMaker of Google Guava (Collections), however I cannot see any good uses of it.

我已经阅读了Javadoc,它说它的行为类似于 WeakHashMap .

I have read the javadoc, and it says that it behaves like ConcurrentHashMap. It also says new MapMaker().weakKeys().makeMap() can almost always be used as a drop-in replacement for WeakHashMap.

但是,请阅读 ConcurrentHashMap

However, reading the javadocs of ConcurrentHashMap and WeakHashMap makes me wonder when it is useful to use it? It seems to me that you cannot have a guarantee that whatever you put in the map will be there, or have I misunderstood?

推荐答案

...这才是重点.如果您不想(或负担不起)在内存中无限期保留对象,则弱引用很有用.考虑以下用例:您需要将信息与类相关联.现在,由于您正在一个可能会重新加载类的环境中运行(例如,Tomcat或OSGi环境),因此您希望垃圾收集器能够在认为安全的情况下尽快回收该类的旧版本.

...and that's somewhat the point of it. Weak references are useful, if you don't want to (or cannot afford to) retain an object indefinetly in memory. Consider the following use case: you need to associate information with classes. Now, since you are running in an environment, where classes might get reloaded (say, a Tomcat, or OSGi environment), you want the garbage collector to be able to reclaim old versions of a class as soon as it deems safe to do so.

实施此操作的初始尝试可能看起来像

An initial attempt to implement this, might look like

class ClassAssoc {
    private final IdentityHashMap<Class<?>,MyMetaData> cache = new ...;
}

这里的问题是:这将使所有类永久保留在cache成员中(或至少将它们保留,除非手动将其删除),从而迫使垃圾收集器不确定地保留它们,包括从该类引用的所有内容(静态成员)值,类加载器信息,...)

The problem here is: this would keep all classes in the cache member forever (or at least, unless they are manually removed), forcing the garbage collector to retain them indefinitly, including everything referenced from the class (static member values, class loader information, ...)

通过使用弱引用,只要不存在对该类的其他引用(通常是实例),垃圾收集器就可以回收该类的旧版本.另一方面:只要存在此类引用,就可以保证该值也可以从弱引用对象访问,因此,它是高速缓存表中的有效键.

By using weak references, the garbage collector can reclaim old version of the class as soon as no other references to it (usually instances) exist. On the other hand: as long as such references exist, the value is guaranteed to be also reachable from the weak reference object, and thus, is a valid key in the cache table.

在图片上添加并发和其他暴行,而您处于MapMaker(可选)还提供的功能...

Add concurrency and other atrocities to the picture, and you are at what MapMaker optionally also provides...

这篇关于有人可以向我解释使用MapMaker或WeakHashMaps何时有用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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