gpt4 book ai didi

java - WeakHashMap 和 WeakReference

转载 作者:行者123 更新时间:2023-12-02 06:41:03 26 4
gpt4 key购买 nike

如何自动清除instanceMap的key和value;当 getInstance() API 返回的 Conf 对象是使用 Wea​​kHashMap 和 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;
}
}
}

最佳答案

如果您想在key被丢弃时进行清理,请使用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();
}

关于java - WeakHashMap 和 WeakReference,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19134401/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com