简体   繁体   English

WeakHashMap和WeakReference

[英]WeakHashMap and WeakReference

How to clear the key and value of instanceMap automatically; 如何自动清除instanceMap的键和值; when the Conf object returned by getInstance() API is Garbage Collected using WeakHashMap and WeakReference ...? 当使用WeakHashMap和WeakReference回收getInstance()API返回的Conf对象时...?

//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;
        }         
    }
}

If you want clean up when the key is discarded, use a WeakHashMap. 如果要在丢弃密钥时进行清理,请使用WeakHashMap。 If you want cleanup on a value is discarded, you need to do this yourself with. 如果要清除某个值,则需要自己进行。

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;
}

Note: this can leave dead key lying around. 注意:这可能会留下死键。 If you don't want this you need to clean them up. 如果您不希望这样做,则需要清理它们。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM