001 /*--------------------------------------------------------------------------+
002 $Id: LRUCacheBase.java 26268 2010-02-18 10:44:30Z juergens $
003 | |
004 | Copyright 2005-2010 Technische Universitaet Muenchen |
005 | |
006 | Licensed under the Apache License, Version 2.0 (the "License"); |
007 | you may not use this file except in compliance with the License. |
008 | 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 edu.tum.cs.commons.cache;
019
020 import java.util.LinkedHashMap;
021
022 import edu.tum.cs.commons.assertion.CCSMPre;
023 import edu.tum.cs.commons.error.NeverThrownRuntimeException;
024
025 /**
026 * A cache with a fixed size using a last recently used (LRU) strategy. If
027 * identifiers itself are suitable hash keys, use class
028 * {@link edu.tum.cs.commons.cache.LRUStraightCacheBase}.
029 *
030 * @author hummelb
031 * @author $Author: juergens $
032 * @version $Rev: 26268 $
033 * @levd.rating GREEN Hash: 7C20602D714E70624D8FF1B0F6BAAEFF
034 *
035 * @param <I>
036 * the index type of the cache
037 * @param <H>
038 * the hash map key type
039 * @param <E>
040 * the type stored in the cache
041 * @param <X>
042 * the type of exception thrown by the {@link #obtainItem(Object)}
043 * method. Use the {@link NeverThrownRuntimeException} if no
044 * exception will be thrown.
045 */
046 public abstract class LRUCacheBase<I, H, E, X extends Exception> extends
047 CacheBase<I, H, E, X> {
048
049 /** The actual cache. */
050 private final LinkedHashMap<H, E> cache;
051
052 /** Constructor. */
053 public LRUCacheBase(final int maxSize) {
054 CCSMPre.isTrue(maxSize > 0, "Maximal size must be positive!");
055
056 cache = new LinkedHashMap<H, E>(2 * maxSize, .6f, true) {
057 @Override
058 protected boolean removeEldestEntry(java.util.Map.Entry<H, E> eldest) {
059 return size() > maxSize;
060 }
061 };
062 }
063
064 /** {@inheritDoc} */
065 @Override
066 public E getItem(I identifier) throws X {
067 H key = getHashKey(identifier);
068 E value = cache.get(key);
069 if (value == null) {
070 value = obtainItem(identifier);
071 cache.put(key, value);
072 }
073 return value;
074 }
075 }