1 16 package org.apache.axis.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 50 public class LRUMap extends SequencedHashMap implements Externalizable { 51 52 private int maximumSize = 0; 53 54 60 public LRUMap() { 61 this( 100 ); 62 } 63 64 71 public LRUMap(int i) { 72 super( i ); 73 maximumSize = i; 74 } 75 76 88 public Object get(Object key) { 89 if(!containsKey(key)) return null; 90 91 Object value = remove(key); 92 super.put(key,value); 93 return value; 94 } 95 96 108 public Object put( Object key, Object value ) { 109 110 int mapSize = size(); 111 Object retval = null; 112 113 if ( mapSize >= maximumSize ) { 114 115 if (!containsKey(key)) { 118 removeLRU(); 120 } 121 } 122 123 retval = super.put(key,value); 124 125 return retval; 126 } 127 128 132 protected void removeLRU() { 133 Object key = getFirstKey(); 134 Object value = super.get(key); 137 138 remove(key); 139 140 processRemovedLRU(key,value); 141 } 142 143 152 protected void processRemovedLRU(Object key, Object value) { 153 } 154 155 public void readExternal( ObjectInput in ) throws IOException , ClassNotFoundException { 158 maximumSize = in.readInt(); 159 int size = in.readInt(); 160 161 for( int i = 0; i < size; i++ ) { 162 Object key = in.readObject(); 163 Object value = in.readObject(); 164 put(key,value); 165 } 166 } 167 168 public void writeExternal( ObjectOutput out ) throws IOException { 169 out.writeInt( maximumSize ); 170 out.writeInt( size() ); 171 for( Iterator iterator = keySet().iterator(); iterator.hasNext(); ) { 172 Object key = iterator.next(); 173 out.writeObject( key ); 174 Object value = super.get( key ); 177 out.writeObject( value ); 178 } 179 } 180 181 182 187 public int getMaximumSize() { 188 return maximumSize; 189 } 190 193 public void setMaximumSize(int maximumSize) { 194 this.maximumSize = maximumSize; 195 while (size() > maximumSize) { 196 removeLRU(); 197 } 198 } 199 200 201 private static final long serialVersionUID = 2197433140769957051L; 204 } 205 | Popular Tags |