Do SoftReference and WeakReference really only help when created as instance variables? Is there any benefit to using them in method scope?
One common thing to do is to create maps of soft references.
Map> cache = new HashMap<>();
Set thingsIAmCurrentlyGetting = new HashSet();
Object mutex = new Object();
BigThing getThing(String key) {
synchronized(mutex) {
while(thingsIAmCurrentlyGetting.contains(key)) {
mutex.wait();
}
SoftReference ref = cache.get(key);
BigThing bigThing = ref == null ? null : ref.get();
if(bigThing != null) return bigThing;
thingsIAmCurrentlyGetting.add(key);
}
BigThing bigThing = getBigThing(key); // this may take a while to run.
synchronized(mutex) {
cache.put(key, bigThing);
thingsIAmCurrentlyGetting.remove(key);
mutex.notifyAll();
}
return bigThing;
}
I'm showing my old school here - the new java packages probably have much neater ways to do this.