/** * Removes the entry from the entry queue. * * @param shuffle indicates whether we are just shuffling the queue (in which case, the entry * table is not modified). */ protected void privateRemoveEntry(LRUCacheEntry entry, boolean shuffle) { LRUCacheEntry previous, next; previous = entry._fPrevious; next = entry._fNext; if (!shuffle) { fEntryTable.remove(entry._fKey); fCurrentSpace -= entry._fSpace; privateNotifyDeletionFromCache(entry); } /* if this was the first entry */ if (previous == null) { fEntryQueue = next; } else { previous._fNext = next; } /* if this was the last entry */ if (next == null) { fEntryQueueTail = previous; } else { next._fPrevious = previous; } }
/** * Sets the value in the cache at the given key. Returns the value. * * @param key Key of object to add. * @param value Value of object to add. * @return added value. */ public Object put(Object key, Object value) { int newSpace, oldSpace, newTotal; LRUCacheEntry entry; /* Check whether there's an entry in the cache */ newSpace = spaceFor(value); entry = (LRUCacheEntry) fEntryTable.get(key); if (entry != null) { /** * Replace the entry in the cache if it would not overflow the cache. Otherwise flush the * entry and re-add it so as to keep cache within budget */ oldSpace = entry._fSpace; newTotal = getCurrentSpace() - oldSpace + newSpace; if (newTotal <= getSpaceLimit()) { updateTimestamp(entry); entry._fValue = value; entry._fSpace = newSpace; this.fCurrentSpace = newTotal; return value; } else { privateRemoveEntry(entry, false); } } if (makeSpace(newSpace)) { privateAdd(key, value, newSpace); } return value; }
/** * Updates the timestamp for the given entry, ensuring that the queue is kept in correct order. * The entry must exist */ protected void updateTimestamp(LRUCacheEntry entry) { entry._fTimestamp = fTimestampCounter++; if (fEntryQueue != entry) { this.privateRemoveEntry(entry, true); this.privateAddEntry(entry, true); } return; }
/** * Adds the given entry from the receiver. * * @param shuffle Indicates whether we are just shuffling the queue (in which case, the entry * table is not modified). */ protected void privateAddEntry(LRUCacheEntry entry, boolean shuffle) { if (!shuffle) { fEntryTable.put(entry._fKey, entry); fCurrentSpace += entry._fSpace; } entry._fTimestamp = fTimestampCounter++; entry._fNext = this.fEntryQueue; entry._fPrevious = null; if (fEntryQueue == null) { /* this is the first and last entry */ fEntryQueueTail = entry; } else { fEntryQueue._fPrevious = entry; } fEntryQueue = entry; }