0
我有一些代碼使用WeakReference
。我不得不實施一個醜陋的解決方法來解決這個問題,但我想知道是否只是增加一個this.synchronized
可能解決我的垃圾收集器的問題。下面是代碼,問題是在功能create
這是否同步保護您的垃圾收集器?
/**
* The canonical map.
*/
var unicityTable = new WeakHashMap[CanonicalType, LightWeightWrapper[CanonicalType]] with SynchronizedMap[CanonicalType, LightWeightWrapper[CanonicalType]]
/**
* Create a new element from any object.
* @param from the object that will be used to generate a new instance of your canonical object.
*/
def create(from: FromType) = {
val newElt = makeFrom(from)
// I wonder if adding a this.synchronized here (and of course removing the test for garbage collection) might solve the problem more elegantly
val wrapper = unicityTable.get(newElt)
wrapper match {
case Some(w) => w._wrap.get match { // if the element is in the map
case Some(element) => element // the element was not garbage collected while we obtaining it
case None => // some how, the wrapped element was garbage collected before we get it, so we recreate it, and put it back
unicityTable.put(newElt, LightWeightWrapper(newElt))
newElt
}
case None => // the element is not in the map
unicityTable.put(newElt, LightWeightWrapper(newElt))
newElt
}
}
class LightWeightWrapper[T <: AnyRef] private (wrap: T) {
val _wrap = new WeakReference(wrap)
def wrapped = _wrap.get match {
case Some(w) => w
case None => // should never happen
throw new IllegalStateException
}
override lazy val hashCode = wrapped.hashCode
override def equals(o: Any): Boolean = o match {
case LightWeightWrapper(w) => w eq this.wrapped
case _ => false
}
}
所以,問題是:是否同步塊的執行過程中的垃圾收集站?