Search code examples
cachinghashmap

Automatic expiry of objects from Hashmap


I have a static hashmap which I am using to cache objects in it. The objects are of different types including lists and hashmaps.

I want to invalidate the objects from the cache after certain time interval. I could add a timestamp to my objects and invalidate them manually. But, I don't know if there is any way I could find the timestamp of when a list was added to the hashmap.

Any comments or suggestions?


Solution

  • Have all the objects which you store in your Hashmap implement a single Expirable interface:

    public interface Expirable {
    
        public Date getExpiryDate();
    }
    

    Once done you'll easily be able to iterate through each element in your Hashmap and remove those which have expired.