1 16 package com.ibatis.sqlmap.engine.cache.lru; 17 18 import java.util.Collections ; 19 import java.util.HashMap ; 20 import java.util.LinkedList ; 21 import java.util.List ; 22 import java.util.Map ; 23 import java.util.Properties ; 24 25 import com.ibatis.sqlmap.engine.cache.CacheController; 26 import com.ibatis.sqlmap.engine.cache.CacheModel; 27 28 31 public class LruCacheController implements CacheController { 32 33 private int cacheSize; 34 private Map cache; 35 private List keyList; 36 37 40 public LruCacheController() { 41 this.cacheSize = 100; 42 this.cache = Collections.synchronizedMap(new HashMap ()); 43 this.keyList = Collections.synchronizedList(new LinkedList ()); 44 } 45 46 51 public void configure(Properties props) { 52 String size = props.getProperty("cache-size"); 53 if (size == null) { 54 size = props.getProperty("size"); 55 } 56 if (size != null) { 57 cacheSize = Integer.parseInt(size); 58 } 59 } 60 61 68 public void putObject(CacheModel cacheModel, Object key, Object value) { 69 cache.put(key, value); 70 keyList.add(key); 71 if (keyList.size() > cacheSize) { 72 try { 73 Object oldestKey = keyList.remove(0); 74 cache.remove(oldestKey); 75 } catch (IndexOutOfBoundsException e) { 76 } 78 } 79 } 80 81 88 public Object getObject(CacheModel cacheModel, Object key) { 89 Object result = cache.get(key); 90 keyList.remove(key); 91 if (result != null) { 92 keyList.add(key); 93 } 94 return result; 95 } 96 97 public Object removeObject(CacheModel cacheModel, Object key) { 98 keyList.remove(key); 99 return cache.remove(key); 100 } 101 102 107 public void flush(CacheModel cacheModel) { 108 cache.clear(); 109 keyList.clear(); 110 } 111 112 } 113 | Popular Tags |