Element cacheNode = (Element)indexTree.get(index);
// The value is cached, return cached value
if(cacheNode != null) {
if(recordHitsOrMisses) cacheHits ++;;
AgedNode agedNode = (AgedNode)cacheNode.get();
value = agedNode.getValue();
cache.remove(cacheNode);
SparseListNode indexNode = agedNode.getIndexNode();
indexNode.setValue(cache.addInSortedOrder((byte)1, agedNode, 1));
// The value is not cached, lookup from source and cache
} else {
if(recordHitsOrMisses) cacheMisses++;
// Make room in the cache if it is full
if(currentSize >= maxSize) {
Element oldestInCache = cache.get(0);
cache.remove(oldestInCache);
AgedNode oldAgedNode = (AgedNode)oldestInCache.get();
SparseListNode oldIndexNode = oldAgedNode.getIndexNode();
indexTree.set(oldIndexNode.getIndex(), null);
currentSize--;
}
// Cache the value
value = source.get(index);
indexTree.set(index, Boolean.TRUE);
SparseListNode indexNode = indexTree.getNode(index);
AgedNode agedNode = new AgedNode(indexNode, value);
indexNode.setValue(cache.addInSortedOrder((byte)1, agedNode, 1));
currentSize++;
}
return value;
}