19 using System.Collections.Generic;
21 namespace Lucene.Net.Util.Cache
23 public class SimpleLRUCache<TKey, TValue> : SimpleMapCache<TKey, TValue>
33 private LinkedList<ListValueEntry<TKey, TValue>> list;
38 private Dictionary<TKey, LinkedListNode<ListValueEntry<TKey, TValue>>> lookup;
43 private LinkedListNode<ListValueEntry<TKey, TValue>> openNode;
45 public SimpleLRUCache(
int Capacity)
47 this.capacity = Capacity;
48 this.list =
new LinkedList<ListValueEntry<TKey, TValue>>();
49 this.lookup =
new Dictionary<TKey, LinkedListNode<ListValueEntry<TKey, TValue>>>(Capacity + 1);
50 this.openNode =
new LinkedListNode<ListValueEntry<TKey, TValue>>(
new ListValueEntry<TKey, TValue>(
default(TKey),
default(TValue)));
53 public override void Put(TKey Key, TValue Value)
57 this.openNode.Value.ItemKey = Key;
58 this.openNode.Value.ItemValue = Value;
59 this.list.AddFirst(this.openNode);
60 this.lookup.Add(Key, this.openNode);
62 if (this.list.Count >
this.capacity)
65 this.openNode = this.list.Last;
68 this.list.RemoveLast();
69 this.lookup.Remove(this.openNode.Value.ItemKey);
74 this.openNode =
new LinkedListNode<ListValueEntry<TKey, TValue>>(
new ListValueEntry<TKey, TValue>(
default(TKey),
default(TValue)));
79 public override TValue Get(
object Key)
81 LinkedListNode<ListValueEntry<TKey, TValue>> node = null;
82 if (!this.lookup.TryGetValue((TKey)Key, out node))
84 return default(TValue);
86 this.list.Remove(node);
87 this.list.AddFirst(node);
88 return node.Value.ItemValue;
95 class ListValueEntry<K, V> where K : TKey
101 internal ListValueEntry(K key, V value)
104 this.ItemValue = value;
110 #region NOT_USED_FROM_JLCA_PORT
124 public class SimpleLRUCache:SimpleMapCache
126 private class AnonymousClassLinkedHashMap : LinkedHashMap
128 public AnonymousClassLinkedHashMap(SimpleLRUCache enclosingInstance)
130 InitBlock(enclosingInstance);
132 private void InitBlock(SimpleLRUCache enclosingInstance)
134 this.enclosingInstance = enclosingInstance;
136 private SimpleLRUCache enclosingInstance;
137 public SimpleLRUCache Enclosing_Instance
141 return enclosingInstance;
145 protected internal virtual bool RemoveEldestEntry(System.Collections.DictionaryEntry eldest)
147 return size() > Enclosing_Instance.cacheSize;
150 private const float LOADFACTOR = 0.75f;
152 private int cacheSize;
155 public SimpleLRUCache(int cacheSize):base(null)
157 this.cacheSize = cacheSize;
158 int capacity = (int) System.Math.Ceiling(cacheSize / LOADFACTOR) + 1;
160 base.map = new AnonymousClassLinkedHashMap(this, capacity, LOADFACTOR, true);