1. /*
  2. * Copyright 2001-2004 The Apache Software Foundation
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package org.apache.commons.collections;
  17. import java.io.Externalizable;
  18. import java.io.IOException;
  19. import java.io.ObjectInput;
  20. import java.io.ObjectOutput;
  21. import java.util.Iterator;
  22. /**
  23. * <p>
  24. * An implementation of a Map which has a maximum size and uses a Least Recently Used
  25. * algorithm to remove items from the Map when the maximum size is reached and new items are added.
  26. * </p>
  27. *
  28. * <p>
  29. * A synchronized version can be obtained with:
  30. * <code>Collections.synchronizedMap( theMapToSynchronize )</code>
  31. * If it will be accessed by multiple threads, you _must_ synchronize access
  32. * to this Map. Even concurrent get(Object) operations produce indeterminate
  33. * behaviour.
  34. * </p>
  35. *
  36. * <p>
  37. * Unlike the Collections 1.0 version, this version of LRUMap does use a true
  38. * LRU algorithm. The keys for all gets and puts are moved to the front of
  39. * the list. LRUMap is now a subclass of SequencedHashMap, and the "LRU"
  40. * key is now equivalent to LRUMap.getFirst().
  41. * </p>
  42. *
  43. * @deprecated Moved to map subpackage. Due to be removed in v4.0.
  44. * @since Commons Collections 1.0
  45. * @version $Revision: 1.23 $ $Date: 2004/02/18 01:15:42 $
  46. *
  47. * @author <a href="mailto:jstrachan@apache.org">James Strachan</a>
  48. * @author <a href="mailto:morgand@apache.org">Morgan Delagrange</a>
  49. */
  50. public class LRUMap extends SequencedHashMap implements Externalizable {
  51. private int maximumSize = 0;
  52. /**
  53. * Default constructor, primarily for the purpose of
  54. * de-externalization. This constructors sets a default
  55. * LRU limit of 100 keys, but this value may be overridden
  56. * internally as a result of de-externalization.
  57. */
  58. public LRUMap() {
  59. this( 100 );
  60. }
  61. /**
  62. * Create a new LRUMap with a maximum capacity of <i>i</i>.
  63. * Once <i>i</i> capacity is achieved, subsequent gets
  64. * and puts will push keys out of the map. See .
  65. *
  66. * @param i Maximum capacity of the LRUMap
  67. */
  68. public LRUMap(int i) {
  69. super( i );
  70. maximumSize = i;
  71. }
  72. /**
  73. * <p>Get the value for a key from the Map. The key
  74. * will be promoted to the Most Recently Used position.
  75. * Note that get(Object) operations will modify
  76. * the underlying Collection. Calling get(Object)
  77. * inside of an iteration over keys, values, etc. is
  78. * currently unsupported.</p>
  79. *
  80. * @param key Key to retrieve
  81. * @return Returns the value. Returns null if the key has a
  82. * null value <i>or</i> if the key has no value.
  83. */
  84. public Object get(Object key) {
  85. if(!containsKey(key)) return null;
  86. Object value = remove(key);
  87. super.put(key,value);
  88. return value;
  89. }
  90. /**
  91. * <p>Removes the key and its Object from the Map.</p>
  92. *
  93. * <p>(Note: this may result in the "Least Recently Used"
  94. * object being removed from the Map. In that case,
  95. * the removeLRU() method is called. See javadoc for
  96. * removeLRU() for more details.)</p>
  97. *
  98. * @param key Key of the Object to add.
  99. * @param value Object to add
  100. * @return Former value of the key
  101. */
  102. public Object put( Object key, Object value ) {
  103. int mapSize = size();
  104. Object retval = null;
  105. if ( mapSize >= maximumSize ) {
  106. // don't retire LRU if you are just
  107. // updating an existing key
  108. if (!containsKey(key)) {
  109. // lets retire the least recently used item in the cache
  110. removeLRU();
  111. }
  112. }
  113. retval = super.put(key,value);
  114. return retval;
  115. }
  116. /**
  117. * This method is used internally by the class for
  118. * finding and removing the LRU Object.
  119. */
  120. protected void removeLRU() {
  121. Object key = getFirstKey();
  122. // be sure to call super.get(key), or you're likely to
  123. // get infinite promotion recursion
  124. Object value = super.get(key);
  125. remove(key);
  126. processRemovedLRU(key,value);
  127. }
  128. /**
  129. * Subclasses of LRUMap may hook into this method to
  130. * provide specialized actions whenever an Object is
  131. * automatically removed from the cache. By default,
  132. * this method does nothing.
  133. *
  134. * @param key key that was removed
  135. * @param value value of that key (can be null)
  136. */
  137. protected void processRemovedLRU(Object key, Object value) {
  138. }
  139. // Externalizable interface
  140. //-------------------------------------------------------------------------
  141. public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException {
  142. maximumSize = in.readInt();
  143. int size = in.readInt();
  144. for( int i = 0; i < size; i++ ) {
  145. Object key = in.readObject();
  146. Object value = in.readObject();
  147. put(key,value);
  148. }
  149. }
  150. public void writeExternal( ObjectOutput out ) throws IOException {
  151. out.writeInt( maximumSize );
  152. out.writeInt( size() );
  153. for( Iterator iterator = keySet().iterator(); iterator.hasNext(); ) {
  154. Object key = iterator.next();
  155. out.writeObject( key );
  156. // be sure to call super.get(key), or you're likely to
  157. // get infinite promotion recursion
  158. Object value = super.get( key );
  159. out.writeObject( value );
  160. }
  161. }
  162. // Properties
  163. //-------------------------------------------------------------------------
  164. /** Getter for property maximumSize.
  165. * @return Value of property maximumSize.
  166. */
  167. public int getMaximumSize() {
  168. return maximumSize;
  169. }
  170. /** Setter for property maximumSize.
  171. * @param maximumSize New value of property maximumSize.
  172. */
  173. public void setMaximumSize(int maximumSize) {
  174. this.maximumSize = maximumSize;
  175. while (size() > maximumSize) {
  176. removeLRU();
  177. }
  178. }
  179. // add a serial version uid, so that if we change things in the future
  180. // without changing the format, we can still deserialize properly.
  181. private static final long serialVersionUID = 2197433140769957051L;
  182. }