001 /**
002 *
003 * Licensed to the Apache Software Foundation (ASF) under one or more
004 * contributor license agreements. See the NOTICE file distributed with
005 * this work for additional information regarding copyright ownership.
006 * The ASF licenses this file to You under the Apache License, Version 2.0
007 * (the "License"); you may not use this file except in compliance with
008 * the License. You may obtain a copy of the License at
009 *
010 * http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018 package org.apache.camel.util;
019
020 import java.util.LinkedHashMap;
021 import java.util.Map;
022
023 /**
024 * A Least Recently Used Cache
025 *
026 * @version $Revision: 1.1 $
027 */
028 public class LRUCache<K, V> extends LinkedHashMap<K, V> {
029 private static final long serialVersionUID = -342098639681884413L;
030 private int maxCacheSize = 10000;
031
032 public LRUCache(int maximumCacheSize) {
033 this(maximumCacheSize, maximumCacheSize, 0.75f, true);
034 }
035
036 /**
037 * Constructs an empty <tt>LRUCache</tt> instance with the
038 * specified initial capacity, maximumCacheSize,load factor and ordering mode.
039 *
040 * @param initialCapacity the initial capacity.
041 * @param maximumCacheSize
042 * @param loadFactor the load factor.
043 * @param accessOrder the ordering mode - <tt>true</tt> for
044 * access-order, <tt>false</tt> for insertion-order.
045 * @throws IllegalArgumentException if the initial capacity is negative
046 * or the load factor is nonpositive.
047 */
048 public LRUCache(int initialCapacity, int maximumCacheSize, float loadFactor, boolean accessOrder) {
049 super(initialCapacity, loadFactor, accessOrder);
050 this.maxCacheSize = maximumCacheSize;
051 }
052
053 /**
054 * @return Returns the maxCacheSize.
055 */
056 public int getMaxCacheSize() {
057 return maxCacheSize;
058 }
059
060 protected boolean removeEldestEntry(Map.Entry entry) {
061 return size() > maxCacheSize;
062 }
063 }