Is there a implementation of java.util.Map that automatically expires its entries when not accessed for specified amount of time. I found many libraries that auto expires entry with some time limits. But I have extra condition. Entry should be removed only when it is not accessed for the time duration.
Asked
Active
Viewed 602 times
0
-
Apache has an AbstractMapDecorator that you could use to make implementing a passive version of this very easy. There's https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/map/PassiveExpiringMap.html already and you could extend it to reset expiration times on access if objects haven't expired yet. Also you've probably already seen this but http://stackoverflow.com/questions/3802370/java-time-based-map-cache-with-expiring-keys for the basic expiring map. Edit: Looks like the answers below are much better. – Jason C Sep 18 '16 at 13:32
2 Answers
3
You can use Guava's cache.
It has two options:
- expireAfterWrite: Expires the entry after a certain period of time since the the entry was added to the cache; or the most recent replacement of the value
- expireAfterAccess: Expires the entry after a certain period of time since the entry was last accessed in the cache.
What you want is number 2.
2
If you want something that gets evicted after a specified amount of time, I would suggest Guavas Cache https://github.com/google/guava/wiki/CachesExplained#timed-eviction
If the entry isn't queried during the time specified, it gets auto-evicted.

qwelyt
- 776
- 9
- 23