sclass Cache {
O maker; // func -> A
A value;
long loaded;
sbool debug;
long changeCount;
Lock lock = lock();
*() {}
*(O *maker) {}
*(IF0 *maker) {}
A get() {
if (hasLock(lock)) ret value; // Must be called from within maker
lock lock;
if (loaded == 0) {
value = make();
changeCount++;
loaded = sysNow();
}
ret value;
}
void clear {
lock lock;
if (debug && loaded != 0)
print("Clearing cache");
value = null;
changeCount++;
loaded = 0;
}
// clear if older than x seconds
// 0 does not do anything
void clear(double seconds) {
lock lock;
if (seconds != 0 && loaded != 0 && sysNow() >= loaded+seconds*1000)
clear();
}
// override
void set(A a) {
lock lock;
value = a;
++changeCount;
loaded = sysNow();
}
A make() {
ret (A) callF(maker);
}
}