1 16 17 package org.springframework.util; 18 19 import java.io.Serializable ; 20 import java.util.Collection ; 21 import java.util.Collections ; 22 import java.util.HashMap ; 23 import java.util.Map ; 24 import java.util.Set ; 25 import java.util.WeakHashMap ; 26 27 import org.apache.commons.logging.Log; 28 import org.apache.commons.logging.LogFactory; 29 30 41 public abstract class CachingMapDecorator implements Map , Serializable { 42 43 private static Object NULL_VALUE = new Object (); 44 45 46 private static final Log logger = LogFactory.getLog(CachingMapDecorator.class); 47 48 private final Map targetMap; 49 50 51 55 public CachingMapDecorator() { 56 this(false); 57 } 58 59 64 public CachingMapDecorator(boolean weakKeys) { 65 Map internalMap = weakKeys ? (Map ) new WeakHashMap () : new HashMap (); 66 this.targetMap = Collections.synchronizedMap(internalMap); 67 } 68 69 75 public CachingMapDecorator(boolean weakKeys, int size) { 76 Map internalMap = weakKeys ? (Map ) new WeakHashMap (size) : new HashMap (size); 77 this.targetMap = Collections.synchronizedMap(internalMap); 78 } 79 80 86 public CachingMapDecorator(Map targetMap) { 87 Assert.notNull(targetMap, "Target Map is required"); 88 this.targetMap = targetMap; 89 } 90 91 92 public int size() { 93 return this.targetMap.size(); 94 } 95 96 public boolean isEmpty() { 97 return this.targetMap.isEmpty(); 98 } 99 100 public boolean containsKey(Object key) { 101 return this.targetMap.containsKey(key); 102 } 103 104 public boolean containsValue(Object value) { 105 return this.targetMap.containsValue(value); 106 } 107 108 public Object put(Object key, Object value) { 109 return this.targetMap.put(key, value); 110 } 111 112 public Object remove(Object key) { 113 return this.targetMap.remove(key); 114 } 115 116 public void putAll(Map t) { 117 this.targetMap.putAll(t); 118 } 119 120 public void clear() { 121 this.targetMap.clear(); 122 } 123 124 public Set keySet() { 125 return this.targetMap.keySet(); 126 } 127 128 public Collection values() { 129 return this.targetMap.values(); 130 } 131 132 public Set entrySet() { 133 return this.targetMap.entrySet(); 134 } 135 136 137 146 public Object get(Object key) { 147 Object value = this.targetMap.get(key); 148 if (value == null) { 149 if (logger.isDebugEnabled()) { 150 logger.debug("Creating new expensive value for key '" + key + "'"); 151 } 152 value = create(key); 153 if (value == null) { 154 value = NULL_VALUE; 155 } 156 if (logger.isDebugEnabled()) { 157 logger.debug("Caching expensive value: " + value); 158 } 159 put(key, value); 160 } 161 else { 162 if (logger.isDebugEnabled()) { 163 logger.debug("For key '" + key + "', returning cached value: " + value); 164 } 165 } 166 return (value == NULL_VALUE) ? null : value; 167 } 168 169 175 protected abstract Object create(Object key); 176 177 178 public String toString() { 179 return "CachingMapDecorator [" + getClass().getName() + "]:" + this.targetMap; 180 } 181 182 } 183 | Popular Tags |