1 2 12 package com.versant.core.server; 13 14 import com.versant.core.jdo.QueryDetails; 15 16 import java.util.Map ; 17 import java.util.HashMap ; 18 19 23 public final class CompiledQueryCache { 24 25 private final int maxSize; 26 private final Map map = new HashMap (); private final Map idMap = new HashMap (); private Entry head, tail; 29 private int lastID; 30 31 private class Entry { 32 CompiledQuery cq; 33 Entry prev, next; 34 } 35 36 public CompiledQueryCache(int maxSize) { 37 this.maxSize = maxSize <= 0 ? 1000 : maxSize; 38 } 39 40 44 public synchronized CompiledQuery get(QueryDetails q) { 45 Entry e = (Entry)map.get(q); 46 if (e == null) { 47 return null; 48 } 49 removeFromLRUList(e); 50 addToHeadOfLRUList(e); 51 return e.cq; 52 } 53 54 58 public synchronized CompiledQuery get(int id) { 59 Entry e = (Entry)idMap.get(new Integer (id)); 60 if (e == null) { 61 return null; 62 } 63 removeFromLRUList(e); 64 addToHeadOfLRUList(e); 65 return e.cq; 66 } 67 68 75 public synchronized CompiledQuery add(CompiledQuery cq) { 76 Entry e = (Entry)map.get(cq.getQueryDetails()); 77 if (e != null) { 78 return e.cq; 79 } 80 e = new Entry(); 81 e.cq = cq; 82 int id = ++lastID; 83 cq.setId(id); 84 map.put(cq.getQueryDetails(), e); 85 idMap.put(new Integer (id), e); 86 addToHeadOfLRUList(e); 87 for (int c = map.size() - maxSize; c > 0; c--) { 88 map.remove(tail.cq.getQueryDetails()); 89 idMap.remove(new Integer (tail.cq.getId())); 90 tail.next.prev = null; 91 tail = tail.next; 92 } 93 return cq; 94 } 95 96 99 public synchronized void clear() { 100 map.clear(); 101 head = tail = null; 102 } 103 104 107 private void removeFromLRUList(Entry e) { 108 if (e.prev != null) { 109 e.prev.next = e.next; 110 } else { 111 tail = e.next; 112 } 113 if (e.next != null) { 114 e.next.prev = e.prev; 115 } else { 116 head = e.prev; 117 } 118 e.next = e.prev = null; 119 } 120 121 125 private void addToHeadOfLRUList(Entry e) { 126 e.next = null; 127 e.prev = head; 128 if (head != null) { 129 head.next = e; 130 } 131 head = e; 132 if (tail == null) { 133 tail = e; 134 } 135 } 136 137 } 138 139 | Popular Tags |