1 19 package org.apache.cayenne.cache; 20 21 import java.io.Serializable ; 22 import java.util.Iterator ; 23 import java.util.List ; 24 import java.util.Map ; 25 26 import org.apache.cayenne.CayenneRuntimeException; 27 import org.apache.cayenne.query.QueryMetadata; 28 import org.apache.commons.collections.map.LRUMap; 29 30 37 public class MapQueryCache implements QueryCache, Serializable { 38 39 public static final int DEFAULT_CACHE_SIZE = 2000; 40 41 protected Map map; 42 43 public MapQueryCache() { 44 this(DEFAULT_CACHE_SIZE); 45 } 46 47 public MapQueryCache(int maxSize) { 48 this.map = new LRUMap(maxSize); 49 } 50 51 public List get(QueryMetadata metadata) { 52 String key = metadata.getCacheKey(); 53 if (key == null) { 54 return null; 55 } 56 57 CacheEntry entry; 58 synchronized (this) { 59 entry = (CacheEntry) map.get(key); 60 } 61 62 return (entry != null) ? entry.list : null; 63 } 64 65 71 public List get(QueryMetadata metadata, QueryCacheEntryFactory factory) { 72 List result = get(metadata); 73 if (result == null) { 74 Object newObject = factory.createObject(); 75 76 if (!(newObject instanceof List )) { 77 if (newObject == null) { 78 throw new CayenneRuntimeException("Null on cache rebuilding: " 79 + metadata.getCacheKey()); 80 } 81 else { 82 throw new CayenneRuntimeException( 83 "Invalid query result, expected List, got " 84 + newObject.getClass().getName()); 85 } 86 } 87 88 result = (List ) newObject; 89 put(metadata, result); 90 } 91 92 return result; 93 } 94 95 public void put(QueryMetadata metadata, List results) { 96 String key = metadata.getCacheKey(); 97 if (key != null) { 98 99 CacheEntry entry = new CacheEntry(); 100 entry.list = results; 101 entry.cacheGroups = metadata.getCacheGroups(); 102 103 synchronized (this) { 104 map.put(key, entry); 105 } 106 } 107 } 108 109 public void remove(String key) { 110 if (key != null) { 111 synchronized (this) { 112 map.remove(key); 113 } 114 } 115 } 116 117 public void removeGroup(String groupKey) { 118 if (groupKey != null) { 119 synchronized (this) { 120 Iterator it = map.values().iterator(); 121 while (it.hasNext()) { 122 CacheEntry entry = (CacheEntry) it.next(); 123 if (entry.cacheGroups != null) { 124 for (int i = 0; i < entry.cacheGroups.length; i++) { 125 126 if (groupKey.equals(entry.cacheGroups[i])) { 127 it.remove(); 128 break; 129 } 130 } 131 } 132 } 133 } 134 } 135 } 136 137 public void clear() { 138 synchronized (this) { 139 map.clear(); 140 } 141 } 142 143 public int size() { 144 return map.size(); 145 } 146 147 final class CacheEntry { 148 149 List list; 150 String [] cacheGroups; 151 } 152 } 153 | Popular Tags |