From 5f02c3fe6ef3e99613c1fe6571e0944f3f491b81 Mon Sep 17 00:00:00 2001 From: "samskivert@gmail.com" Date: Fri, 5 Aug 2005 02:41:24 +0000 Subject: [PATCH] Allow a value in an LRU hash map to be notified when it gets the boot. git-svn-id: https://samskivert.googlecode.com/svn/trunk@1685 6335cc39-0255-0410-8fd6-9bcaacd3b74c --- .../java/com/samskivert/util/LRUHashMap.java | 25 ++++++++++++++++--- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/projects/samskivert/src/java/com/samskivert/util/LRUHashMap.java b/projects/samskivert/src/java/com/samskivert/util/LRUHashMap.java index 3bd05904..5747fcbe 100644 --- a/projects/samskivert/src/java/com/samskivert/util/LRUHashMap.java +++ b/projects/samskivert/src/java/com/samskivert/util/LRUHashMap.java @@ -31,6 +31,17 @@ public class LRUHashMap implements Map public int computeSize (Object item); } + /** + * Values in the LRU hash map that implement this interface will be + * notified when they are removed from the table (either explicitly or + * by being replaced with another value or due to being flushed). + */ + public static interface LRUItem + { + /** Informs this item that it was removed from the map. */ + public void removedFromMap (LRUHashMap map); + } + /** * Construct a LRUHashMap with the specified maximum size. All items * in the cache will be considered to have a size of one. @@ -170,10 +181,13 @@ public class LRUHashMap implements Map _seenKeys.add(key); } - // updated our computed "size" - _size += _sizer.computeSize(value); - entryRemoved(result); + // avoid fruitless NOOPs + if (result != value) { + // updated our computed "size" + _size += _sizer.computeSize(value); + entryRemoved(result); // System.out.println("Added " + value + ": " + _size); + } // flush if needed flush(); @@ -199,7 +213,7 @@ public class LRUHashMap implements Map Iterator iter = _delegate.entrySet().iterator(); // don't remove the last entry, even if it's too big, because // a cache with nothing in it sucks - for (int ii=size(); (ii > 1) && (_size > _maxSize); ii--) { + for (int ii = size(); (ii > 1) && (_size > _maxSize); ii--) { Map.Entry entry = (Map.Entry) iter.next(); entryRemoved(entry.getValue()); iter.remove(); @@ -214,6 +228,9 @@ public class LRUHashMap implements Map { if (entry != null) { _size -= _sizer.computeSize(entry); + if (entry instanceof LRUItem) { + ((LRUItem)entry).removedFromMap(this); + } } }