📄 cache.java
字号:
return map.containsKey(key); } public void putAll(Map<? extends K, ? extends V> map) { for (Iterator<? extends K> i = map.keySet().iterator(); i.hasNext();) { K key = i.next(); V value = map.get(key); put(key, value); } } public boolean containsValue(Object value) { // First, clear all entries that have been in cache longer than the // maximum defined age. deleteExpiredEntries(); if(value == null) { return containsNullValue(); } Iterator it = values().iterator(); while(it.hasNext()) { if(value.equals(it.next())) { return true; } } return false; } private boolean containsNullValue() { Iterator it = values().iterator(); while(it.hasNext()) { if(it.next() == null) { return true; } } return false; } public Set entrySet() { // First, clear all entries that have been in cache longer than the // maximum defined age. deleteExpiredEntries(); // TODO Make this work right return Collections.unmodifiableSet(map.entrySet()); } public Set<K> keySet() { // First, clear all entries that have been in cache longer than the // maximum defined age. deleteExpiredEntries(); return Collections.unmodifiableSet(map.keySet()); } /** * Returns the name of this cache. The name is completely arbitrary * and used only for display to administrators. * * @return the name of this cache. */ public String getName() { return name; } /** * Returns the number of cache hits. A cache hit occurs every * time the get method is called and the cache contains the requested * object.<p> * * Keeping track of cache hits and misses lets one measure how efficient * the cache is; the higher the percentage of hits, the more efficient. * * @return the number of cache hits. */ public long getCacheHits() { return cacheHits; } /** * Returns the number of cache misses. A cache miss occurs every * time the get method is called and the cache does not contain the * requested object.<p> * * Keeping track of cache hits and misses lets one measure how efficient * the cache is; the higher the percentage of hits, the more efficient. * * @return the number of cache hits. */ public long getCacheMisses() { return cacheMisses; } /** * Returns the size of the cache contents in bytes. This value is only a * rough approximation, so cache users should expect that actual VM * memory used by the cache could be significantly higher than the value * reported by this method. * * @return the size of the cache contents in bytes. */ public int getCacheSize() { return cacheSize; } /** * Returns the maximum size of the cache (in bytes). If the cache grows larger * than the max size, the least frequently used items will be removed. If * the max cache size is set to -1, there is no size limit. * * @return the maximum size of the cache (-1 indicates unlimited max size). */ public int getMaxCacheSize() { return maxCacheSize; } /** * Sets the maximum size of the cache. If the cache grows larger * than the max size, the least frequently used items will be removed. If * the max cache size is set to -1, there is no size limit. * * @param maxCacheSize the maximum size of this cache (-1 indicates unlimited max size). */ public void setMaxCacheSize(int maxCacheSize) { this.maxCacheSize = maxCacheSize; // It's possible that the new max size is smaller than our current cache // size. If so, we need to delete infrequently used items. cullCache(); } /** * Returns the maximum number of milleseconds that any object can live * in cache. Once the specified number of milleseconds passes, the object * will be automatically expried from cache. If the max lifetime is set * to -1, then objects never expire. * * @return the maximum number of milleseconds before objects are expired. */ public long getMaxLifetime() { return maxLifetime; } /** * Sets the maximum number of milleseconds that any object can live * in cache. Once the specified number of milleseconds passes, the object * will be automatically expried from cache. If the max lifetime is set * to -1, then objects never expire. * * @param maxLifetime the maximum number of milleseconds before objects are expired. */ public void setMaxLifetime(long maxLifetime) { this.maxLifetime = maxLifetime; } /** * Returns the size of an object in bytes. Determining size by serialization * is only used as a last resort. * * @return the size of an object in bytes. */ private int calculateSize(Object object) { // If the object is Cacheable, ask it its size. if (object instanceof Cacheable) { return ((Cacheable)object).getCachedSize(); } // Check for other common types of objects put into cache. else if (object instanceof Long) { return CacheSizes.sizeOfLong(); } else if (object instanceof Integer) { return CacheSizes.sizeOfObject() + CacheSizes.sizeOfInt(); } else if (object instanceof Boolean) { return CacheSizes.sizeOfObject() + CacheSizes.sizeOfBoolean(); } else if (object instanceof long[]) { long[] array = (long[])object; return CacheSizes.sizeOfObject() + array.length * CacheSizes.sizeOfLong(); } else if (object instanceof byte[]) { byte [] array = (byte[])object; return CacheSizes.sizeOfObject() + array.length; } // Default behavior -- serialize the object to determine its size. else { int size = 1; try { // Default to serializing the object out to determine size. NullOutputStream out = new NullOutputStream(); ObjectOutputStream outObj = new ObjectOutputStream(out); outObj.writeObject(object); size = out.size(); } catch (IOException ioe) { Log.error(ioe); } return size; } } /** * Clears all entries out of cache where the entries are older than the * maximum defined age. */ protected void deleteExpiredEntries() { // Check if expiration is turned on. if (maxLifetime <= 0) { return; } // Remove all old entries. To do this, we remove objects from the end // of the linked list until they are no longer too old. We get to avoid // any hash lookups or looking at any more objects than is strictly // neccessary. LinkedListNode node = ageList.getLast(); // If there are no entries in the age list, return. if (node == null) { return; } // Determine the expireTime, which is the moment in time that elements // should expire from cache. Then, we can do an easy to check to see // if the expire time is greater than the expire time. long expireTime = System.currentTimeMillis() - maxLifetime; while (expireTime > node.timestamp) { // Remove the object remove(node.object); // Get the next node. node = ageList.getLast(); // If there are no more entries in the age list, return. if (node == null) { return; } } } /** * Removes objects from cache if the cache is too full. "Too full" is * defined as within 3% of the maximum cache size. Whenever the cache is * is too big, the least frequently used elements are deleted until the * cache is at least 10% empty. */ protected final void cullCache() { // Check if a max cache size is defined. if (maxCacheSize < 0) { return; } // See if the cache size is within 3% of being too big. If so, clean out // cache until it's 10% free. if (cacheSize >= maxCacheSize * .97) { // First, delete any old entries to see how much memory that frees. deleteExpiredEntries(); int desiredSize = (int)(maxCacheSize * .90); while (cacheSize > desiredSize) { // Get the key and invoke the remove method on it. remove(lastAccessedList.getLast().object); } } } /** * Wrapper for all objects put into cache. It's primary purpose is to maintain * references to the linked lists that maintain the creation time of the object * and the ordering of the most used objects. */ private static class CacheObject<V> { /** * Underlying object wrapped by the CacheObject. */ public V object; /** * The size of the Cacheable object. The size of the Cacheable * object is only computed once when it is added to the cache. This makes * the assumption that once objects are added to cache, they are mostly * read-only and that their size does not change significantly over time. */ public int size; /** * A reference to the node in the cache order list. We keep the reference * here to avoid linear scans of the list. Every time the object is * accessed, the node is removed from its current spot in the list and * moved to the front. */ public LinkedListNode lastAccessedListNode; /** * A reference to the node in the age order list. We keep the reference * here to avoid linear scans of the list. The reference is used if the * object has to be deleted from the list. */ public LinkedListNode ageListNode; /** * A count of the number of times the object has been read from cache. */ public int readCount = 0; /** * Creates a new cache object wrapper. The size of the Cacheable object * must be passed in in order to prevent another possibly expensive * lookup by querying the object itself for its size.<p> * * @param object the underlying Object to wrap. * @param size the size of the Cachable object in bytes. */ public CacheObject(V object, int size) { this.object = object; this.size = size; } } /** * An extension of OutputStream that does nothing but calculate the number * of bytes written through it. */ private static class NullOutputStream extends OutputStream { int size = 0; public void write(int b) throws IOException { size++; } public void write(byte[] b) throws IOException { size += b.length; } public void write(byte[] b, int off, int len) { size += len; } /** * Returns the number of bytes written out through the stream. * * @return the number of bytes written to the stream. */ public int size() { return size; } }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -