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.fusesource.hawtdb.util; 018 019 import java.util.LinkedHashMap; 020 import java.util.Map; 021 022 /** 023 * A Simple LRU Cache 024 * 025 * @param <K> 026 * @param <V> 027 */ 028 029 public class LRUCache<K, V> extends LinkedHashMap<K, V> { 030 private static final long serialVersionUID = -342098639681884413L; 031 protected int maxCacheSize = 10000; 032 033 /** 034 * Default constructor for an LRU Cache The default capacity is 10000 035 */ 036 public LRUCache() { 037 this(0,10000, 0.75f, true); 038 } 039 040 /** 041 * Constructs a LRUCache with a maximum capacity 042 * 043 * @param maximumCacheSize 044 */ 045 public LRUCache(int maximumCacheSize) { 046 this(0, maximumCacheSize, 0.75f, true); 047 } 048 049 /** 050 * Constructs an empty <tt>LRUCache</tt> instance with the specified 051 * initial capacity, maximumCacheSize,load factor and ordering mode. 052 * 053 * @param initialCapacity the initial capacity. 054 * @param maximumCacheSize 055 * @param loadFactor the load factor. 056 * @param accessOrder the ordering mode - <tt>true</tt> for access-order, 057 * <tt>false</tt> for insertion-order. 058 * @throws IllegalArgumentException if the initial capacity is negative or 059 * the load factor is non-positive. 060 */ 061 062 public LRUCache(int initialCapacity, int maximumCacheSize, float loadFactor, boolean accessOrder) { 063 super(initialCapacity, loadFactor, accessOrder); 064 this.maxCacheSize = maximumCacheSize; 065 } 066 067 /** 068 * @return Returns the maxCacheSize. 069 */ 070 public int getMaxCacheSize() { 071 return maxCacheSize; 072 } 073 074 /** 075 * @param maxCacheSize The maxCacheSize to set. 076 */ 077 public void setMaxCacheSize(int maxCacheSize) { 078 this.maxCacheSize = maxCacheSize; 079 } 080 081 protected boolean removeEldestEntry(Map.Entry<K,V> eldest) { 082 return size() > maxCacheSize; 083 } 084 }