1 7 8 9 package com.hp.hpl.jena.db.impl; 12 13 import java.util.*; 16 17 import com.hp.hpl.jena.shared.JenaException; 18 import com.hp.hpl.jena.util.CollectionFactory; 19 20 21 29 30 public class LRUCache implements ICache { 31 32 54 55 protected Map keyCache; 56 protected Map valCache; 57 58 protected IDBID Keys[]; 59 protected Random rand; 60 61 public LRUCache(int max) { 62 rand = new Random(); 63 resize(max); 64 } 65 66 protected void resize ( int max ) { 67 maxCount = max; 68 keyCache = CollectionFactory.createHashedMap(max); 69 valCache = CollectionFactory.createHashedMap(max); 70 Keys = new IDBID[max]; 71 count = 0; 72 } 73 74 protected int maxCount; 75 protected int count; 76 77 public Object get(IDBID id) { 78 return keyCache.get(id); 79 } 80 81 public Object getByValue(String val) { 82 return valCache.get(val); 83 } 84 85 86 public void put(IDBID id, Object val) { 87 synchronized (this) { 88 int curSize = keyCache.size(); 89 keyCache.put(id, val); 90 valCache.put(val,id); 91 if (keyCache.size() > curSize) { 92 int ix = count++; 93 if (count > maxCount) { 94 ix = rand.nextInt(maxCount); 97 Object keyval = keyCache.get(Keys[ix]); 98 if ( (keyval == null) || (keyCache.remove(Keys[ix]) == null) ) 99 throw new JenaException("LRUCache keyCache corrupted"); 100 if ( valCache.remove(keyval) == null ) 101 throw new JenaException("LRUCache valCache corrupted"); 102 count--; 103 Keys[ix] = id; 104 if (keyCache.size() > maxCount) 105 throw new JenaException("LRUCache exceeds threshold"); 106 } 107 Keys[ix] = id; 108 } 109 } 110 } 111 112 120 121 public void clear() { 122 keyCache.clear(); 123 valCache.clear(); 124 count = 0; 125 } 126 127 133 public void setLimit(int max) { 134 resize(max); 135 } 136 137 public int getLimit() { 138 return maxCount; 139 } 140 141 } 142 168 169 170 | Popular Tags |