本文介绍了Java中有SoftHashMap吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我知道java.util中有一个WeakHashMap,但由于它使用WeakReferences来处理所有事件,只有这个Map引用了它,所以在下一个GC循环中引用的对象将会丢失。所以如果你想要缓存随机数据,这几乎是没有用的,而随机数据很可能会在没有与其他时间硬连接的情况下再次被请求。最好的解决方案是使用SoftReferences代替的映射,但是我没有在Java RT Package中找到一个映射。 解决方案编辑(2012年8月): 事实证明,目前最好的解决方案可能是Guava 13.0的 Cache 类,在番石榴的Wiki 中解释 - 这就是我将要使用的。 它甚至支持构建 SoftHashMap (请参阅 CacheBuilder.newBuilder()。softKeys()),但它可能不是你想要的,正如Java专家Jeremy Manson所解释的那样(下面你会发现这个链接)。 不是我知道(2008年11月),但你会发现一些在网上实现 SoftHashMap 。 像这样: SoftHashMap 或 this one 。 编辑(2009年11月) 由于 Matthias 在评论中提及,谷歌Guava MapMaker 的确使用SoftReferences: 编辑(2012年8月) ) 只有在请求条目超时时,Google实现才会使用后台线程。特别是,它只是简单地使用 java.util.Timer ,这不像拥有一个单独的后台线程那么具有侵入性。 http://jeremymanson.blogspot.de/2009/07/how-hotspot-decides-to-clear_07.html 还有 Apache Commons 的另一个实现,即;它不支持定时删除,但它支持选择是否应通过身份或平等来比较密钥。此外,这个实现并不是并发的 - 它可以被同步,但是在多线程访问的情况下效果不太理想。 I know there is a WeakHashMap in java.util, but since it uses WeakReferences for everything, which is only referenced by this Map, referenced objects will get lost on the next GC cycle. So it's nearly useless if you want to cache random data, which is very likely to be requested again without being Hard-linked the rest of the time. The best solution would be a map, which uses SoftReferences instead, but i didn't find one in the Java RT Package. 解决方案 Edit (Aug. 2012):It turns out that currently the best solution are probably Guava 13.0's Cache classes, explained on Guava's Wiki - that's what I'm going to use.It even supports building a SoftHashMap (see CacheBuilder.newBuilder().softKeys()), but it is probably not what you want, as Java expert Jeremy Manson explains (below you'll find the link).Not that I know of (Nov. 2008), but you kind find some implementation of SoftHashMap on the net.Like this one: SoftHashMap or this one.Edit (Nov. 2009)As Matthias mentions in the comments, the Google Guava MapMaker does use SoftReferences:As mentioned in this thread, another JSR166y candidate:jsr166y.ConcurrentReferenceHashMapEdit (August 2012)The Google implementation uses a background thread only when timed expiration of entries is requested. In particular, it simply uses java.util.Timer, which is not so intrusive as having a separate background thread.Jeremy Manson recommends, for any cache, using this feature to avoid the dangers of SoftReference:http://jeremymanson.blogspot.de/2009/07/how-hotspot-decides-to-clear_07.htmlThere's another implementation from Apache Commons, namely org.apache.commons.collections.map.ReferenceMap; it does not support timed removal, but it does support choosing whether keys should be compared by identity or by equality. Moreover, this implementation is not concurrent - it can be made synchronized, but that works less well under accesses from multiple threads. 这篇关于Java中有SoftHashMap吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-20 09:28