I'm implementing a cache for Objects stored persistently. The idea is:
- Method
getObjectFromPersistence(long id); ///Takes about 3 seconds
- Method
getObjectFromCache(long id) //Instantly
And have a method: getObject(long id)
with the following pseudocode:
synchronized(this){
CustomObject result= getObjectFromCache(id)
if (result==null){
result=getObjectFromPersistence(id);
addToCache(result);
}
return result;
}
But I need to allow the CustomObject to be collected by the garbage collector. Until now I was using an HashMap<Long,WeakReference<CustomObject>
for the implementation. The problem is that over the time the HashMap becomes filled of empty WeakReferences
.
I've checked WeakHashMap but there the keys are weak (and the values are still strong references) so having the longs with WeakReferences have no sense.
Whats the best solution for solving this problem? Is there some "inverse WeakHashMap" or something similar?
Thanks