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