1 16 package org.apache.commons.collections; 17 18 import java.io.Externalizable ; 19 import java.io.IOException ; 20 import java.io.ObjectInput ; 21 import java.io.ObjectOutput ; 22 import java.util.Iterator ; 23 24 52 public class LRUMap extends SequencedHashMap implements Externalizable { 53 54 private int maximumSize = 0; 55 56 62 public LRUMap() { 63 this( 100 ); 64 } 65 66 73 public LRUMap(int i) { 74 super( i ); 75 maximumSize = i; 76 } 77 78 90 public Object get(Object key) { 91 if(!containsKey(key)) return null; 92 93 Object value = remove(key); 94 super.put(key,value); 95 return value; 96 } 97 98 110 public Object put( Object key, Object value ) { 111 112 int mapSize = size(); 113 Object retval = null; 114 115 if ( mapSize >= maximumSize ) { 116 117 if (!containsKey(key)) { 120 removeLRU(); 122 } 123 } 124 125 retval = super.put(key,value); 126 127 return retval; 128 } 129 130 134 protected void removeLRU() { 135 Object key = getFirstKey(); 136 Object value = super.get(key); 139 140 remove(key); 141 142 processRemovedLRU(key,value); 143 } 144 145 154 protected void processRemovedLRU(Object key, Object value) { 155 } 156 157 public void readExternal( ObjectInput in ) throws IOException , ClassNotFoundException { 160 maximumSize = in.readInt(); 161 int size = in.readInt(); 162 163 for( int i = 0; i < size; i++ ) { 164 Object key = in.readObject(); 165 Object value = in.readObject(); 166 put(key,value); 167 } 168 } 169 170 public void writeExternal( ObjectOutput out ) throws IOException { 171 out.writeInt( maximumSize ); 172 out.writeInt( size() ); 173 for( Iterator iterator = keySet().iterator(); iterator.hasNext(); ) { 174 Object key = iterator.next(); 175 out.writeObject( key ); 176 Object value = super.get( key ); 179 out.writeObject( value ); 180 } 181 } 182 183 184 189 public int getMaximumSize() { 190 return maximumSize; 191 } 192 195 public void setMaximumSize(int maximumSize) { 196 this.maximumSize = maximumSize; 197 while (size() > maximumSize) { 198 removeLRU(); 199 } 200 } 201 202 203 private static final long serialVersionUID = 2197433140769957051L; 206 } 207 | Popular Tags |