我知道这个问题是针对java的 https://stackoverflow.com/questions/264582/is-there-a-softhashmap-in-java,但这些实现似乎都不能很好地配合scala.collection.JavaConversions
.
我正在寻找简单的东西(例如单个文件,不是整个图书馆)实现SoftHashMap
这样它就能很好地与 Scala 配合使用Map
(即支持getOrElseUpdate
, unzip
,剩下的 ScalaMap
方法)。
实施灵感来自这个javaWeakHashMap http://www.koders.com/java/fidF6A9D06D716A6B562853A8DA95C43169F4044FC0.aspx?s=idef%3Aconfiguration:
import scala.collection.mutable.{Map, HashMap}
import scala.ref._
class SoftMap[K, V <: AnyRef] extends Map[K, V]
{
class SoftValue[K, +V <: AnyRef](val key:K, value:V, queue:ReferenceQueue[V]) extends SoftReference(value, queue)
private val map = new HashMap[K, SoftValue[K, V]]
private val queue = new ReferenceQueue[V]
override def += (kv: (K, V)): this.type =
{
processQueue
val sv = new SoftValue(kv._1, kv._2, queue)
map(kv._1) = sv
this
}
private def processQueue
{
while (true)
{
queue.poll match
{
case Some(sv:SoftValue[K, _]) => map.remove(sv.key)
case _ => return
}
}
}
override def get(key: K): Option[V] = map.get(key) match
{
case Some(sv) => sv.get match
{ case v:Some[_] => v
case None => {map.remove(key); None} }
case None => None
}
override def -=(key: K):this.type =
{
processQueue
map.remove(key)
this
}
override def iterator: Iterator[(K, V)] =
{
processQueue
map.iterator.collect{ case (key, sv) if sv.get.isDefined => (key, sv.get.get) }
}
override def empty:SoftMap[K, V] = new SoftMap[K, V]
override def size = {processQueue; map.size}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)