0

如何自动清除instanceMap的key和value;当 getInstance() API 返回的 Conf 对象是 Garbage Collected using 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;
        }         
    }
}
4

1 回答 1

2

如果要在丢弃密钥时进行清理,请使用 Wea​​kHashMap。如果你想清理一个值被丢弃,你需要自己做。

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();
}
于 2013-10-02T10:09:06.720 回答