I am trying to create a cache that holds a messageID and a responsePayload (both bytes[]), and ensuring that each item in the cache expires after 5 seconds. Here is what I am currently trying to do.
I have the following class:
public class CacheObject {
public byte[] responsePayload;
public long time;
public CacheObject(byte[] responsePayload) {
this.responsePayload = responsePayload;
this.time = System.currentTimeMillis();
}
}
Using this class I have created the following cache with messageID as the key and CacheObject as the value
private static HashMap<byte[], CacheObject> cache = new HashMap<byte[], CacheObject>();
Then I call a function everytime I loop through the main part of my program:
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();
}
}
}
However the problem I am facing is I cannot seem to assign the iterator object to my CacheObject in this line:
CacheObject cacheObject = itr.next();
I've seen a few posts where this is suggested, but it does not seem to work for me. Is there a way around this issue, or is there a better way to implement this cache removal?