/** * Adds a new Cacheable object to the cache. The key must be unique. * * @param key a unique key for the object being put into cache. * @param object the Cacheable object to put into cache. */ public synchronized void add(long key, Cacheable object) { // Delete an old entry if it exists. if (object == null) return; remove(key); long objectSize = object.getSize(); if (objectSize == -1) objectSize = CacheSizes.cacheSizeOfObject(object); // If the object is bigger than the entire cache, simply don't add it. if (objectSize > maxObjectSize) { return; } size += objectSize; LongCacheObject cacheObject = new LongCacheObject(object, objectSize); cachedObjectsHash.put(key, cacheObject); // Make an entry into the cache order list. LongLinkedListNode lastAccessedNode = lastAccessedList.addFirst(key); // StoreImp the cache order list entry so that we can get back to it // during later lookups. cacheObject.lastAccessedListNode = lastAccessedNode; // Add the object to the age list LongLinkedListNode ageNode = ageList.addFirst(key); // We make an explicit call to currentTimeMillis() so that total accuracy // of lifetime calculations is better than one second. ageNode.timestamp = System.currentTimeMillis(); cacheObject.ageListNode = ageNode; // If cache is too full, remove least used cache entries until it is // not too full. if (size >= maxSize) { cullCache(); } }
/** * Removes an object from cache. * * @param key the unique key of the object to remove. */ public synchronized void remove(long key) { LongCacheObject cacheObject = (LongCacheObject) cachedObjectsHash.get(key); // If the object is not in cache, stop trying to remove it. if (cacheObject == null) { return; } // remove from the hash map cachedObjectsHash.removeKey(key); // remove from the cache order list cacheObject.lastAccessedListNode.remove(); cacheObject.ageListNode.remove(); // remove references to linked list nodes cacheObject.ageListNode = null; cacheObject.lastAccessedListNode = null; // removed the object, so subtract its size from the total. size -= cacheObject.size; }