LRUCache_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > LRUCache

LRUCache

 2014/5/20 13:09:41  hyl198611  程序员俱乐部  我要评论(0)
  • 摘要:packagecommon;importjava.util.LinkedHashMap;importjava.util.concurrent.locks.Lock;importjava.util.concurrent.locks.ReentrantLock;/****@Title:LRUCache.java*@Copyright:Copyright(c)2011*@Description:<br>LRUCache本地缓存*<br>*@Company:renren
  • 标签:

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);?

?

  • 相关文章
发表评论
用户名: 匿名