1 22 23 28 29 package org.xquark.mapper.util; 30 31 import java.util.Collection ; 32 import java.util.Iterator ; 33 34 38 public class CacheManager 39 { 40 private static final String RCSRevision = "$Revision: 1.1 $"; 41 private static final String RCSName = "$Name: $"; 42 43 private CounterMap usedObjects = new CounterMap(); 44 private LRU cache; 45 private int cacheSize; 46 47 48 public CacheManager(int cacheSize) 49 { 50 this.cacheSize = cacheSize; 51 cache = new LRU(cacheSize); 52 } 53 54 public Object checkOut(Object key) 55 { 56 Object o = usedObjects.checkOut(key); 57 58 if (o == null) 60 { 61 o = cache.get(key); 62 if (o != null) 64 use(key, o); 65 } 66 return o; 67 } 68 69 70 public void use(Object key, Object o) 71 { 72 usedObjects.put(key, o); 73 74 int lruSize = cacheSize - usedObjects.size(); 75 if (lruSize >= 0) 76 cache.setMaxSize(lruSize); 77 } 78 79 82 public Object release(Object key) 83 { 84 Object removed = usedObjects.remove(key); 85 86 if (removed != null) 88 { 89 cache.setMaxSize(cacheSize - usedObjects.size()); 90 removed = cache.put(key, removed); 91 } 92 return removed; 93 } 94 95 96 public void put(Object key, Object o) 97 { 98 cache.put(key, o); 99 } 100 101 102 public Object get(Object key) 103 { 104 Object o = usedObjects.get(key); 105 106 if (o == null) 107 o = cache.get(key); 108 return o; 109 } 110 111 public boolean contains(Object key) 112 { 113 return get(key) != null; 114 } 115 116 public int size() 117 { 118 return usedObjects.size() + cache.size(); 119 } 120 121 public int getCacheSize() 122 { 123 return cacheSize; 124 } 125 126 public void clear() 127 { 128 usedObjects.clear(); 129 cache.clear(); 130 } 131 132 public boolean used() 133 { 134 return usedObjects.size() > 0; 135 } 136 137 public boolean used(Object key) 138 { 139 return usedObjects.containsKey(key); 140 } 141 142 public void setKey(Object oldKey, Object newKey) 143 { 144 usedObjects.setKey(oldKey, newKey); 145 cache.setKey(oldKey, newKey); 146 } 147 148 public Object remove(Object key) 149 { 150 Object removed = cache.removeObject(key); 151 152 removed = usedObjects.removeAll(key); 153 if (removed != null) 154 cache.setMaxSize(cacheSize - usedObjects.size()); 155 return removed; 156 } 157 158 public Iterator iterator() 159 { 160 Collection objects = usedObjects.values(); 161 objects.addAll(cache.values()); 162 return objects.iterator(); 163 } 164 } 165 | Popular Tags |