// (c) Tuomas J. Lukka package org.fenfire.util; import java.util.*; import org.nongnu.navidoc.util.CachingMap; import org.nongnu.libvob.util.Background; import org.fenfire.*; import org.fenfire.util.*; /** A base class for superlazy caches. */ public class SuperLazyBase { protected CachingMap cache; protected Object placeHolder; protected Background background; protected ObjObs recalcObs; /** Create a new SuperLazyBase. * @param n The number of cache entries to use * @param placeHolder The value to return when no function value * has been precalculated. * @param background The object to use for the background calculations. * @param recalcObs The observer to call whenever a new value * has been calculated */ public SuperLazyBase(int n, Object placeHolder, Background background, ObjObs recalcObs ) { this.placeHolder = placeHolder; this.background = background; this.recalcObs = recalcObs; cache = new CachingMap(n); } protected abstract class CacheEntry extends FunctionCacheEntry implements Runnable, CachingMap.Removable { public CacheEntry(Object input) { super(input); } public void schedule() { background.addTask(this, 0); } public void wasRemoved(Object key) { this.obses = null; // free them background.removeTask(this); } /** Get the cache value or schedule. * If the value is cached, return it, otherwise * schedule to be evaluated and return the placeholder. */ public Object getValueAndSchedule() { if(value == DIRTY) { schedule(); return placeHolder; } return value; } } }