I'm currently working with a Guava cache generated by Guava's cache builder and it has methods to remove all values, remove a set of values by key, and to remove a value by key. No, I cannot just not store the null values because they need to be stored for around 5 minutes.
Is there a better way to remove all null values after N minutes besides completely reimplementing a new cache where I can setup expireAfterWriteNanos when setting a value, or something like:
schedule at fixed rate(
() -> {
iterate through all keys to save which ones have null values
cache.invalidate(iterable of all of those keys)
},
5 minutes
);
I prefer not to use this method because it's expensive to iterate through all of the keys
There is nothing much better than what you describe, but I challenge the assumption that it's necessarily expensive to iterate through all the keys, especially, as you describe, doing it in a background task.
You could, of course, have your cache's "values" store your current values and a time they were created, and then have your cache lookups check that null values are no older than a certain time.