2013-10-02 73 views
0

如何自動清除instanceMap的鍵和值;當getInstance()API返回的Conf對象使用WeakHashMap和WeakReference ...進行垃圾回收時?WeakHashMap和WeakReference

//single conference instance per ConferenceID 
class Conf { 

    private static HashMap<String, Conf> instanceMap = new HashMap<String, Conf>; 

    /* 
    * Below code will avoid two threads are requesting 
    * to create conference with same confID. 
    */ 
    public static Conf getInstance(String confID){ 
     //This below synch will ensure singleTon created per confID 
     synchronized(Conf.Class) { 
      Conf conf = instanceMap.get(confID); 
      if(conf == null) { 
       conf = new Conf(); 
       instanceMap.put(confID, conf); 
      } 
      return conf; 
     }   
    } 
} 

回答

2

如果你想清理時被丟棄,使用WeakHashMap中。如果你想清除一個值被丟棄,你需要自己做這個。

private static final Map<String, WeakReference<Conf>> instanceMap = new HashMap<>; 

/* 
* Below code will avoid two threads are requesting 
* to create conference with same confID. 
*/ 
public static synchronized Conf getInstance(String confID){ 
    //This below synch will ensure singleTon created per confID 

    WeakReference<Conf> ref = instanceMap.get(confID); 
    Conf conf; 
    if(ref == null || (conf = ref.get()) == null) { 
     conf = new Conf(); 
     instanceMap.put(confID, new WeakReference<Conf>(conf)); 
    } 
    return conf; 
} 

注意:這可能會導致死鎖無效。如果你不想要這個,你需要清理它們。

for(Iterator<WeakReference<Conf>> iter = instanceMap.values().iterator(); iter.hashNext() ;) { 
    WeakReference<Conf> ref = iter.next(); 
    if (ref.get() == null) iter.remove(); 
} 
+0

謝謝!彼得。但是,你能否合併兩者?我不想要死鑰匙,並且我不想運行單獨的線程來使用迭代清理死鑰匙。 –

+0

@KanagaveluSugumar您可以通過將循環放入方法中。 –