1 22 23 28 29 package org.xquark.mapper.util; 30 31 import java.util.*; 32 33 37 public class LRU extends LinkedList 38 { 39 private static final String RCSRevision = "$Revision: 1.1 $"; 40 private static final String RCSName = "$Name: $"; 41 42 private int maxSize; 43 private HashMap index; 44 45 46 public LRU(int maxSize) 47 { 48 setMaxSize(maxSize); 49 index = new HashMap(); 50 } 51 52 public void setMaxSize(int maxSize) 53 { 54 while (size() > maxSize) { 56 Node node = (Node)remove(0); 57 index.remove(node.key); 58 } 59 this.maxSize = maxSize; 60 } 61 62 public int getMaxSize() 63 { 64 return maxSize; 65 } 66 67 70 public Object put(Object key, Object o) 71 { 72 Object discarded = null; 73 if (maxSize > 0) 74 { 75 Node node = new Node(key, o); 76 super.add(node); 77 index.put(key, node); 78 if (size() > maxSize) { 80 node = (Node)remove(0); 81 index.remove(node.key); 82 discarded = node.o; 83 } 84 } 85 else 86 discarded = o; 87 88 return discarded; 89 } 90 91 public Object get(Object key) 92 { 93 Node node = (Node)index.get(key); 94 if (node != null) 96 { 97 add(remove(indexOf(node))); 98 return node.o; 99 } 100 else 101 return null; 102 } 103 104 public void clear() 105 { 106 super.clear(); 107 index.clear(); 108 } 109 110 public synchronized void setKey(Object oldKey, Object newKey) 111 { 112 Node node = (Node)index.remove(oldKey); 113 if (node != null) 114 { 115 node.key = newKey; 116 index.put(newKey, node); 117 } 118 } 119 120 public Object removeObject(Object key) 121 { 122 Node removed = (Node)index.remove(key); 123 if (removed != null) 124 super.remove(removed); 125 return removed; 126 } 127 128 public Collection values() 129 { 130 ArrayList list = new ArrayList(); 131 Iterator it = super.iterator(); 132 while (it.hasNext()) 133 { 134 list.add(((Node)it.next()).o); 135 } 136 return list; 137 } 138 139 private class Node 140 { 141 Object key; 142 Object o; 143 144 Node(Object key, Object o) 145 { 146 this.key = key; 147 this.o = o; 148 } 149 } 150 } 151 | Popular Tags |