mjn mjn - 1 year ago 53
Java Question

Object cache data structure with "object expiration"

Which data structure in Java would be best to implement an in-memory object cache, where objects have an individual expiration time?

Basically for the cache I could use a Map (where key could be a String) which offers the put and get methods, and use a ordered list of "timestamp"+"object" pairs to manage the expiration time. So a cleanup thread could check the first list entry and delete the object when its expiration time passed. (Deletion of the first element should be in O(1) time)

Answer Source

What you're describing building is basically ExpiringMap. There are other similar implementations, such as Guava (see CacheBuilder) - though I don't believe it supports per-entry expiration as ExpiringMap does.