1 8 9 package com.hp.hpl.jena.util.cache; 10 11 import java.util.Collection ; 12 import java.util.HashMap ; 13 import java.util.Iterator ; 14 15 import org.apache.commons.logging.Log; 16 import org.apache.commons.logging.LogFactory; 17 18 22 public class RandCache implements Cache, CacheControl { 23 int size; 24 int threshhold; 25 boolean enabled = true; 26 String name; 29 HashMap map; 30 Collection collection; 31 32 protected static Log logger = LogFactory.getLog(RandCache.class); 33 34 long gets = 0; 35 long puts = 0; 36 long hits = 0; 37 38 39 RandCache(String name, int size) { 40 this.size = size; 41 try { 42 map = new HashMap (size * 100 / 75); } catch (IllegalArgumentException e) { 44 if ("Illegal load factor: NaN".equals(e.getMessage())) { 45 logger.warn("Detected a NaN anomaly believed to be due to use of JDK 1.4.1"); 54 map = new HashMap (size*100/75, 0.75f); 55 } else { 56 throw e; 57 } 58 } 59 threshhold = size; 60 if (threshhold < 2) { 61 throw new Error ("Cache size too small: " + size); 62 } 63 collection = map.values(); 64 } 65 66 public synchronized Object get(Object key) { 67 if (enabled) { 68 if (gets == Long.MAX_VALUE) { 69 forgetStats(); 70 } 71 gets++; 72 Object result = map.get(key); 73 if (result != null) { 74 hits++; 75 } 76 return result; 77 } else { 78 return null; 79 } 80 } 81 82 public synchronized void put(Object key, Object value) { 83 84 if (value == null) { 86 throw new NullPointerException (); 87 } 88 89 if (enabled) { 90 if (puts == Long.MAX_VALUE) { 91 forgetStats(); 92 } 93 puts++; 94 if (map.size() >= threshhold) { 95 makeSpace(); 96 } 97 map.put(key, value); 98 } 99 } 100 101 protected void makeSpace() { 102 Iterator iter = collection.iterator(); 103 104 int size = map.size(); 106 int i = 3; 107 while (i < size ) { 108 iter.next(); 109 iter.remove(); 110 iter.next(); 111 iter.next(); 112 i = i + 3; 113 } 114 } 115 116 public synchronized boolean getEnabled() { 117 return enabled; 118 } 119 120 public synchronized boolean setEnabled(boolean enabled) { 121 boolean result = enabled; 122 this.enabled = enabled; 123 return result; 124 } 125 126 public synchronized void clear() { 127 map.clear(); 128 } 129 130 public synchronized long getHits() { 131 return hits; 132 } 133 134 public synchronized long getGets() { 135 return gets; 136 } 137 138 public synchronized long getPuts() { 139 return puts; 140 } 141 142 protected void forgetStats() { 143 gets = gets/2; 144 puts = puts/2; 145 hits = hits/2; 146 } 147 148 } 149 179 | Popular Tags |