1 16 package com.ibatis.sqlmap.engine.cache.memory; 17 18 import com.ibatis.sqlmap.engine.cache.CacheController; 19 import com.ibatis.sqlmap.engine.cache.CacheModel; 20 21 import java.lang.ref.SoftReference ; 22 import java.lang.ref.WeakReference ; 23 import java.util.Collections ; 24 import java.util.HashMap ; 25 import java.util.Map ; 26 import java.util.Properties ; 27 28 31 public class MemoryCacheController implements CacheController { 32 33 private MemoryCacheLevel cacheLevel = MemoryCacheLevel.WEAK; 34 private Map cache = Collections.synchronizedMap(new HashMap ()); 35 36 41 public void configure(Properties props) { 42 String refType = props.getProperty("reference-type"); 43 if (refType == null) { 44 refType = props.getProperty("referenceType"); 45 } 46 if (refType != null) { 47 cacheLevel = MemoryCacheLevel.getByReferenceType(refType); 48 } 49 } 50 51 58 public void putObject(CacheModel cacheModel, Object key, Object value) { 59 Object reference = null; 60 if (cacheLevel.equals(MemoryCacheLevel.WEAK)) { 61 reference = new WeakReference (value); 62 } else if (cacheLevel.equals(MemoryCacheLevel.SOFT)) { 63 reference = new SoftReference (value); 64 } else if (cacheLevel.equals(MemoryCacheLevel.STRONG)) { 65 reference = new StrongReference(value); 66 } 67 cache.put(key, reference); 68 } 69 70 77 public Object getObject(CacheModel cacheModel, Object key) { 78 Object value = null; 79 Object ref = cache.get(key); 80 if (ref != null) { 81 if (ref instanceof StrongReference) { 82 value = ((StrongReference) ref).get(); 83 } else if (ref instanceof SoftReference ) { 84 value = ((SoftReference ) ref).get(); 85 } else if (ref instanceof WeakReference ) { 86 value = ((WeakReference ) ref).get(); 87 } 88 } 89 return value; 90 } 91 92 public Object removeObject(CacheModel cacheModel, Object key) { 93 Object value = null; 94 Object ref = cache.remove(key); 95 if (ref != null) { 96 if (ref instanceof StrongReference) { 97 value = ((StrongReference) ref).get(); 98 } else if (ref instanceof SoftReference ) { 99 value = ((SoftReference ) ref).get(); 100 } else if (ref instanceof WeakReference ) { 101 value = ((WeakReference ) ref).get(); 102 } 103 } 104 return value; 105 } 106 107 112 public void flush(CacheModel cacheModel) { 113 cache.clear(); 114 } 115 116 119 private static class StrongReference { 120 private Object object; 121 122 126 public StrongReference(Object object) { 127 this.object = object; 128 } 129 130 134 public Object get() { 135 return object; 136 } 137 } 138 139 } 140 | Popular Tags |