package common;
import java.util.LinkedHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
?*
?* @Title: LRUCache.java
?* @Copyright: Copyright (c) 2011
?* @Description: <br>LRUCache 本地缓存
?*?????????????? <br>
?* @Company: renren.com
?* @Created on 2014-1-14 下午1:25:55
?* @author youle.heng
?*/
public class LRUCache <K, V> extends LinkedHashMap<K, V> {
???
??? private static final long serialVersionUID = -8021134033779621716L;
??? private final int maxCapacity;
??? private static final float DEFAULT_LOAD_FACTOR = 0.75f;
??? private final Lock lock = new ReentrantLock();
??? public LRUCache(int maxCapacity) {
??????? super(maxCapacity, DEFAULT_LOAD_FACTOR, true);
??????? this.maxCapacity = maxCapacity;
??? }
??? @Override
??? protected boolean removeEldestEntry(java.util.Map.Entry<K, V> eldest) {
??????? return size() > maxCapacity;
??? }
??? /**
???? * Weather contains someone Object according to a key
???? * @param key
???? */
??? @Override
??? public boolean containsKey(Object key) {
??????? lock.lock();
??????? try {
??????????? return super.containsKey(key);
??????? } finally {
??????????? lock.unlock();
??????? }
??? }
??? /**
???? * Get one Object according to a key
???? * @param key
???? */
??? @Override
??? public V get(Object key) {
??????? lock.lock();
??????? try {
??????????? return super.get(key);
??????? } finally {
??????????? lock.unlock();
??????? }
??? }
??? /**
???? * Put an Object to cache
???? * @param key,value
???? */
??? @Override
??? public V put(K key, V value) {
??????? lock.lock();
??????? try {
??????????? return super.put(key, value);
??????? } finally {
??????????? lock.unlock();
??????? }
??? }
??? /**
???? * The cache's size
???? */
??? public int size() {
??????? lock.lock();
??????? try {
??????????? return super.size();
??????? } finally {
??????????? lock.unlock();
??????? }
??? }
??? /**
???? * clear the cache
???? */
??? public void clear() {
??????? lock.lock();
??????? try {
??????????? super.clear();
??????? } finally {
??????????? lock.unlock();
??????? }
??? }
??? /**
???? * Delete one Object from cache
???? *
???? * @param key
???? */
??? public void delete(Object key) {
??????? lock.lock();
??????? try {
??????????? super.remove(key);
??????? } finally {
??????????? lock.unlock();
??????? }
??? }
}
new 一个能存储50个值的LRUCache对象
LRUCache<String,String> mc = new LRUCache<String,String>(50);?
?