我正在尝试创建一个保存 messageID 和 responsePayload(均为 bytes[])的缓存,并确保缓存中的每个项目在 5 秒后过期。这是我目前正在尝试做的事情。
我有以下类(class):
public class CacheObject {
public byte[] responsePayload;
public long time;
public CacheObject(byte[] responsePayload) {
this.responsePayload = responsePayload;
this.time = System.currentTimeMillis();
}
}
使用此类,我创建了以下缓存,其中 messageID 作为键,CacheObject 作为值
private static HashMap<byte[], CacheObject> cache = new HashMap<byte[], CacheObject>();
然后,每次循环程序的主要部分时,我都会调用一个函数:
private static void updateCache() {
Collection times = cache.values();
Iterator itr = times.iterator();
while(itr.hasNext()) {
CacheObject cacheObject = itr.next();
if(System.currentTimeMillis() - cacheObject.time > 5000) {
itr.remove();
}
}
}
但是我面临的问题是我似乎无法在这一行中将迭代器对象分配给我的 CacheObject:
CacheObject cacheObject = itr.next();
我看过一些建议这样做的帖子,但它似乎对我不起作用。有没有办法解决这个问题,或者有更好的方法来实现缓存删除?
最佳答案
不要使用原始类型!您收到该错误是因为您的迭代器类型不正确。将其声明为:
Collection<CacheObject> times = cache.values();
Iterator<CacheObject> itr = times.iterator();
<小时/>
编辑:
有一种更好的方法来实现 updateCache
方法:
private static void updateCache() {
cache.values().removeIf(c -> System.currentTimeMillis() - c.time > 5000);
}
其中 c
的类型为 CacheObject
,与 map 值的类型匹配。
检查Collection.removeIf
方法文档以供进一步引用。
关于java - 在设定的时间段后从缓存中删除项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48394491/