1 package org.apache.ojb.broker.cache; 2 3 17 18 import org.apache.commons.lang.builder.ToStringBuilder; 19 import org.apache.commons.lang.builder.ToStringStyle; 20 import org.apache.ojb.broker.Identity; 21 import org.apache.ojb.broker.PersistenceBroker; 22 23 import java.lang.ref.SoftReference ; 24 import java.util.HashMap ; 25 import java.util.Map ; 26 import java.util.Properties ; 27 28 65 public class ObjectCacheLocalDefaultImpl implements ObjectCache 66 { 67 private static final String TIMEOUT = "timeout"; 68 69 72 protected Map objectTable = new HashMap (); 73 74 77 private long timeout = 1000 * 60 * 15; 78 79 82 public ObjectCacheLocalDefaultImpl(PersistenceBroker broker, Properties prop) 83 { 84 timeout = prop == null ? timeout : ( Long.parseLong( prop.getProperty( TIMEOUT, "" + timeout ) ) )*1000; 85 } 86 87 90 public void clear() 91 { 92 objectTable.clear(); 93 } 94 95 100 public void cache(Identity oid, Object obj) 101 { 102 if ((obj != null)) 103 { 104 SoftReference ref = new SoftReference (new CacheEntry(obj)); 105 objectTable.put(oid, ref); 106 } 107 } 108 109 public boolean cacheIfNew(Identity oid, Object obj) 110 { 111 if(objectTable.get(oid) == null) 112 { 113 cache(oid, obj); 114 return true; 115 } 116 return false; 117 } 118 119 123 public Object lookup(Identity oid) 124 { 125 CacheEntry entry = null; 126 SoftReference ref = (SoftReference ) objectTable.get(oid); 127 if (ref != null) 128 { 129 entry = (CacheEntry) ref.get(); 130 if (entry == null || entry.lifetime < System.currentTimeMillis()) 131 { 132 objectTable.remove(oid); entry = null; 135 } 136 } 137 return entry != null ? entry.object : null; 138 } 139 140 143 public void remove(Identity oid) 144 { 145 if (oid != null) 146 { 147 objectTable.remove(oid); 148 } 149 } 150 151 public String toString() 152 { 153 ToStringBuilder buf = new ToStringBuilder(this, ToStringStyle.DEFAULT_STYLE); 154 buf.append("Count of cached objects", objectTable.keySet().size()); 155 return buf.toString(); 156 } 157 158 class CacheEntry 162 { 163 long lifetime; 164 Object object; 165 166 public CacheEntry(Object object) 167 { 168 this.object = object; 169 lifetime = System.currentTimeMillis() + timeout; 170 } 171 } 172 173 } 174 | Popular Tags |