1 package org.apache.oro.util; 2 3 59 60 import java.util.*; 61 62 75 public final class CacheLRU extends GenericCache { 76 private int __head = 0, __tail = 0; 77 private int[] __next, __prev; 78 79 84 public CacheLRU(int capacity) { 85 super(capacity); 86 87 int i; 88 89 __next = new int[_cache.length]; 90 __prev = new int[_cache.length]; 91 92 for(i=0; i < __next.length; i++) 93 __next[i] = __prev[i] = -1; 94 } 95 96 97 103 public CacheLRU(){ 104 this(GenericCache.DEFAULT_CAPACITY); 105 } 106 107 108 private void __moveToFront(int index) { 109 int next, prev; 110 111 if(__head != index) { 112 next = __next[index]; 113 prev = __prev[index]; 114 115 __next[prev] = next; 118 119 if(next >= 0) 122 __prev[next] = prev; 123 else 124 __tail = prev; 125 126 __prev[index] = -1; 127 __next[index] = __head; 128 __prev[__head] = index; 129 __head = index; 130 } 131 } 132 133 134 public synchronized Object getElement(Object key) { 135 Object obj; 136 137 obj = _table.get(key); 138 139 if(obj != null) { 140 GenericCacheEntry entry; 141 142 entry = (GenericCacheEntry)obj; 143 __moveToFront(entry._index); 145 146 return entry._value; 147 } 148 149 return null; 150 } 151 152 153 161 public final synchronized void addElement(Object key, Object value) { 162 int index; 163 Object obj; 164 165 obj = _table.get(key); 166 167 if(obj != null) { 168 GenericCacheEntry entry; 169 170 entry = (GenericCacheEntry)obj; 172 entry._value = value; 173 entry._key = key; 174 175 __moveToFront(entry._index); 176 177 return; 178 } 179 180 if(!isFull()) { 183 if(_numEntries > 0) { 184 __prev[_numEntries] = __tail; 185 __next[_numEntries] = -1; 186 __moveToFront(_numEntries); 187 } 188 ++_numEntries; 189 } else { 190 _table.remove(_cache[__tail]._key); 192 __moveToFront(__tail); 193 } 194 195 _cache[__head]._value = value; 196 _cache[__head]._key = key; 197 _table.put(key, _cache[__head]); 198 } 199 } 200 | Popular Tags |