Reputation: 394
I have a class which extends LinkedHashMap
which I'm using as a cache. This cache has a property which defines the maximum size in bytes that the cache is allowed to store. I use a rough estimate for the size of the objects that I store.
I override put
, so that I update the total size that the cache is currently storing.
I also override remove
to subtract the size of the object I've removed from the total.
At the moment I'm checking whether or not I need to remove stale entries from the cache to free up space on adding a new value in the put
method, however I would like to move this functionality to an implementation of the removeEldestEntry
method.
The problem I've encountered is that it seems if my overridden removeEldestEntry
returns true
, my overridden remove
method is not called. This leads to a problem where my current stored size variable is not updated when the removeEldestEntry
removes stale entries.
Does anyone know what code path is taken to remove the eldest entry when removeEldestEntry
returns true
. Is it possible for me to override the method that this uses to remove entries?
Is it possible for me to do my update calculation when LinkedHashMap
triggers a removal on removeEldestEntry
.
I know the api allows you to do the actual removal in the removeEldestEntry
method as long as you return false afterwards, however I want to explore other options before doing this. I view this as a last case scenario.
Upvotes: 0
Views: 1329
Reputation: 140318
Looking at the source code of LinkedHashMap where removeEldestEntry
is called, it doesn't call remove
, but instead calls removeNode
- which is also called in the default implementation of remove
.
Note that this is sort of an example of the Fragile Base Class problem, wherein you are attempting to rely upon an implementation detail in the base class (i.e. if removeEldestEntry
returns true, remove
is called) that isn't actually true - the difference is that it is already not true, rather than it becoming not true at some point in the future.
You might want to consider implementing your own wrapper class around the LinkedHashMap
which delegates a lot of the behavior to LHM, but in which you implement the specific eviction logic that you want.
Upvotes: 3