gpt4 book ai didi

java - 我可以/应该将 ConcurrentMap 与我自己的缓存一起使用吗?

转载 作者:行者123 更新时间:2023-11-30 05:09:10 24 4
gpt4 key购买 nike

很多人将 ConcurrentMap 称为缓存。

这样做是个好主意吗:

public List<Task> listTasks(final ProcessDefinition def, final boolean filterEnumerated) {
final String CACHENAME = def.getName() + "-v" + def.getVersion() + "-Tasks";
ConcurrentMap<String, List<Task>> cache = (ConcurrentMap<String, List<Task>>) Contexts.getApplicationContext().get(CACHENAME);
if (Contexts.getApplicationContext().isSet(CACHENAME) && cache != null) {
return cache.get(CACHENAME);
} else {

ConcurrentMap<String, List<Task>> myTasks = new MapMaker()
.softValues()
.expiration(2L, TimeUnit.HOURS)
.makeComputingMap(
new Function<String, List<Task>>() {
@Override
public List<Task> apply(String from) {
return getTasksFromDefinition(def, filterEnumerated);
}
});

myTasks.put(CACHENAME, getTasksFromDefinition(def, filterEnumerated));

Contexts.getApplicationContext().set(CACHENAME,myTasks);
Collection<List<Task>> tz = myTasks.values();
//First element in the collection
return new ArrayList<Task>(tz.iterator().next());
}
}

或者是否有必要使用ApplicationContext(这是java-ee应用程序上下文)来缓存映射,并且只从映射中检索值?
类似于此post的答案

我还想知道.expiration(2L, TimeUnit.HOURS)。这真的是 2 小时吗?还是 long 的值以毫秒为单位?

最佳答案

我个人认为将这样的缓存存储在 ApplicationContext 中是可以的,因为它是线程安全的。但请注意缓存的大小,尤其是在集群等情况下。

关于过期问题,如您所料,过期时间为 2 小时。

关于java - 我可以/应该将 ConcurrentMap 与我自己的缓存一起使用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4070157/

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