001 /* 002 @license.text@ 003 */ 004 package biz.hammurapi.cache; 005 006 import java.util.HashMap; 007 import java.util.HashSet; 008 import java.util.Iterator; 009 import java.util.Map; 010 import java.util.Set; 011 012 import biz.hammurapi.config.ConfigurationException; 013 import biz.hammurapi.util.Acceptor; 014 015 016 /** 017 * Simple cache. Uses map internally. 018 * @author Pavel Vlasov 019 * @version $Revision: 1.3 $ 020 */ 021 public class SimpleMemoryCache extends AbstractProducer implements Cache { 022 private Map cache=new HashMap(); 023 private Producer producer; 024 025 /** 026 * 027 */ 028 public SimpleMemoryCache(Producer producer) { 029 super(); 030 031 this.producer=producer; 032 if (producer!=null) { 033 producer.addCache(this); 034 } 035 036 } 037 038 public void put(Object key, final Object value, final long time, final long expirationTime) { 039 synchronized (cache) { 040 cache.put(key, new Entry() { 041 042 public long getExpirationTime() { 043 return expirationTime; 044 } 045 046 public long getTime() { 047 return time; 048 } 049 050 public Object get() { 051 return value; 052 } 053 054 }); 055 } 056 } 057 058 public Entry get(Object key) { 059 060 synchronized (cache) { 061 Entry entry=(Entry) cache.get(key); 062 long now = System.currentTimeMillis(); 063 if (entry!=null) { 064 if (entry.getExpirationTime()>0 && entry.getExpirationTime()<now) { 065 cache.remove(key); 066 } else { 067 return entry; 068 } 069 } 070 071 if (key instanceof ProducingKey) { 072 entry = ((ProducingKey) key).get(); 073 cache.put(key, entry); 074 return entry; 075 } 076 077 if (producer!=null) { 078 entry = producer.get(key); 079 cache.put(key, entry); 080 return entry; 081 } 082 083 return null; 084 } 085 } 086 087 public void clear() { 088 synchronized (cache) { 089 cache.clear(); 090 } 091 } 092 093 public void remove(Object key) { 094 synchronized (cache) { 095 cache.remove(key); 096 } 097 onRemove(key); 098 } 099 100 public void remove(Acceptor acceptor) { 101 synchronized (cache) { 102 Iterator it=cache.keySet().iterator(); 103 while (it.hasNext()) { 104 Object key=it.next(); 105 if (acceptor.accept(key)) { 106 it.remove(); 107 onRemove(key); 108 } 109 } 110 } 111 } 112 113 public void stop() { 114 cache.clear(); 115 } 116 117 public Set keySet() { 118 HashSet ret = new HashSet(); 119 synchronized (cache) { 120 ret.addAll(cache.keySet()); 121 } 122 123 if (producer!=null) { 124 Set pkeys=producer.keySet(); 125 if (pkeys!=null) { 126 ret.addAll(pkeys); 127 } 128 } 129 130 return ret; 131 } 132 133 public boolean isActive() { 134 return true; 135 } 136 137 public void start() throws ConfigurationException { 138 // Nothing 139 } 140 141 public void setOwner(Object owner) { 142 // Nothing 143 } 144 }