Scala中有SoftHashMap吗? [英] Is there a SoftHashMap in Scala?
本文介绍了Scala中有SoftHashMap吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道这个java的问题,但没有一个这些实现似乎很好用 scala.collection.JavaConversions
。
I'm aware of this question for java, but none of those implementations seem to play well with scala.collection.JavaConversions
.
我正在寻找简单的东西(例如单个文件,不是整个库),实现 SoftHashMap
,使其与Scala
Map
(即支持 getOrElseUpdate
,解压缩
,剩余的Scala Map
方法)
I'm looking for something simple (e.g. single file, not a whole library) that implements SoftHashMap
such that it plays well with Scala Map
(i.e. supports getOrElseUpdate
, unzip
, and the remaining Scala Map
methods).
推荐答案
实现灵感来自这个java WeakHashMap
:
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}
}
这篇关于Scala中有SoftHashMap吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文