user3504410
user3504410

Reputation: 183

Removing items from a cache after a set period?

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?

Upvotes: 1

Views: 798

Answers (1)

fps
fps

Reputation: 34470

Don't use raw types! You are getting that error because your iterator is not correctly typed. Declare it as:

Collection<CacheObject> times = cache.values();
Iterator<CacheObject> itr = times.iterator();

Edit:

There's a much better way to implement your updateCache method:

private static void updateCache() {
    cache.values().removeIf(c -> System.currentTimeMillis() - c.time > 5000);
}

Where c is of type CacheObject, matching the type of the values of your map.

Check Collection.removeIf method docs for further reference.

Upvotes: 2

Related Questions