The Algorithm
How to Read This
onAccess runs every time an item is requested. If it's already
cached, its scores get updated and added to its running total. If it's not cached and there's
no room, selectEvictionCandidate firsty looks for items
whose scores have "converged" and are confirmed useless and removes the one with the highest
running total among those. If nothing qualifies, it falls back to removing the item with the
highest running total overall.
class CacheItem {
double T, I1, I2, F;
double integralSum;
double p;
long lastAccess;
List<Long> accessIntervals;
}
class NeutrosophicCache {
Map<String, CacheItem> cache;
int capacity;
double deltaThreshold;
void onAccess(String key) {
long now = System.currentTimeMillis();
if (cache.containsKey(key)) {
CacheItem item = cache.get(key);
double dt = now - item.lastAccess;
item.T = computeTruth(item);
item.I1 = computeContradiction(item);
item.I2 = computeIgnorance(item);
item.F = computeFalsity(item, now);
item.integralSum += (item.T + item.I1 + item.I2) * dt;
item.accessIntervals.add((long) dt);
item.p = estimateP(item.accessIntervals);
item.lastAccess = now;
} else {
onMiss(key, now);
}
}
void onMiss(String key, long now) {
if (cache.size() >= capacity) {
String victim = selectEvictionCandidate();
cache.remove(victim);
}
CacheItem newItem = new CacheItem();
newItem.lastAccess = now;
newItem.integralSum = 0;
newItem.p = 1.5;
cache.put(key, newItem);
}
String selectEvictionCandidate() {
List<String> candidates = new ArrayList<>();
for (Map.Entry<String, CacheItem> entry : cache.entrySet()) {
CacheItem item = entry.getValue();
boolean integralConverges = item.p > 1;
boolean falsityExceeded = item.F >= deltaThreshold;
if (integralConverges && falsityExceeded) {
candidates.add(entry.getKey());
}
}
if (candidates.isEmpty()) {
return cache.entrySet().stream()
.max(Comparator.comparingDouble(e -> e.getValue().integralSum))
.get().getKey();
}
return candidates.stream()
.max(Comparator.comparingDouble(k -> cache.get(k).integralSum))
.orElseThrow();
}
}
NEXT