Sea*_*oyd 241 java caching dictionary
你们是否知道Java Map或类似的标准数据存储在给定的超时后自动清除条目?这意味着老化,旧的过期条目会自动"老化".
最好是在可通过Maven访问的开源库中?
我知道自己实现这些功能的方法,并且过去曾多次这样做过,所以我不是在这方面寻求建议,而是指向一个好的参考实现.
基于WeakReference的解决方案(如WeakHashMap)不是一个选项,因为我的键很可能是非实习字符串,我想要一个不依赖于垃圾收集器的可配置超时.
Ehcache也是一个我不想依赖的选项,因为它需要外部配置文件.我正在寻找一个仅限代码的解决方案.
She*_*ari 307
是.谷歌集合,或现在命名的番石榴有一个名为MapMaker的东西可以做到这一点.
ConcurrentMap<Key, Graph> graphs = new MapMaker()
.concurrencyLevel(4)
.softKeys()
.weakValues()
.maximumSize(10000)
.expiration(10, TimeUnit.MINUTES)
.makeComputingMap(
new Function<Key, Graph>() {
public Graph apply(Key key) {
return createExpensiveGraph(key);
}
});
Run Code Online (Sandbox Code Playgroud)
更新:
从guava 10.0(2011年9月28日发布)开始,许多这些MapMaker方法已被弃用,以支持新的CacheBuilder:
LoadingCache<Key, Graph> graphs = CacheBuilder.newBuilder()
.maximumSize(10000)
.expireAfterWrite(10, TimeUnit.MINUTES)
.build(
new CacheLoader<Key, Graph>() {
public Graph load(Key key) throws AnyException {
return createExpensiveGraph(key);
}
});
Run Code Online (Sandbox Code Playgroud)
Viv*_*vek 24
这是我为同一要求所做的示例实现,并发性很好.可能对某人有用.
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
*
* @author Vivekananthan M
*
* @param <K>
* @param <V>
*/
public class WeakConcurrentHashMap<K, V> extends ConcurrentHashMap<K, V> {
private static final long serialVersionUID = 1L;
private Map<K, Long> timeMap = new ConcurrentHashMap<K, Long>();
private long expiryInMillis = 1000;
private static final SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss:SSS");
public WeakConcurrentHashMap() {
initialize();
}
public WeakConcurrentHashMap(long expiryInMillis) {
this.expiryInMillis = expiryInMillis;
initialize();
}
void initialize() {
new CleanerThread().start();
}
@Override
public V put(K key, V value) {
Date date = new Date();
timeMap.put(key, date.getTime());
System.out.println("Inserting : " + sdf.format(date) + " : " + key + " : " + value);
V returnVal = super.put(key, value);
return returnVal;
}
@Override
public void putAll(Map<? extends K, ? extends V> m) {
for (K key : m.keySet()) {
put(key, m.get(key));
}
}
@Override
public V putIfAbsent(K key, V value) {
if (!containsKey(key))
return put(key, value);
else
return get(key);
}
class CleanerThread extends Thread {
@Override
public void run() {
System.out.println("Initiating Cleaner Thread..");
while (true) {
cleanMap();
try {
Thread.sleep(expiryInMillis / 2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void cleanMap() {
long currentTime = new Date().getTime();
for (K key : timeMap.keySet()) {
if (currentTime > (timeMap.get(key) + expiryInMillis)) {
V value = remove(key);
timeMap.remove(key);
System.out.println("Removing : " + sdf.format(new Date()) + " : " + key + " : " + value);
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
干杯!!
Gur*_*nov 17
Apache Commons有Map的装饰器使条目到期:PassiveExpiringMap 它比Guava的缓存更简单.
PS小心,它不同步.
| 归档时间: |
|
| 查看次数: |
160962 次 |
| 最近记录: |