2014-04-17 58 views
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 
    } 
    } 

所以,問題是:是否同步塊的執行過程中的垃圾收集站?

回答

2

不,垃圾收集仍然發生在​​裏面。此外,this已被阻止垃圾收集,因爲它在堆棧中,所以你也沒有得到任何幫助。

我不確定你在做什麼,但我想也許你真的想用SoftReference而不是WeakReference。只有在所有硬引用消失時纔會收集僅由WeakReference引用的對象。可以保留僅由SoftReference引用的對象,直到虛擬機內存不足。