ibatis 源码分享1---FifoCacheController

最近在学习Ibatis 源码,看到FifoCacheController在项目很有用途分享大家

package com.ibatis.sqlmap.engine.cache.fifo;

import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import com.ibatis.sqlmap.engine.cache.CacheController;
import com.ibatis.sqlmap.engine.cache.CacheModel;

/**
* FIFO (first in, first out) cache controller implementation
*/
public class FifoCacheController implements CacheController {

private int cacheSize;
private Map cache;
private List keyList;

/**
* Default constructor
*/
public FifoCacheController() {
this.cacheSize = 100;

//用Map放key value 可以用ConcurrentHashMap优化性能
this.cache = Collections.synchronizedMap(new HashMap());
//用LinkedList放key
this.keyList = Collections.synchronizedList(new LinkedList());
}

public int getCacheSize() {
return cacheSize;
}

public void setCacheSize(int cacheSize) {
this.cacheSize = cacheSize;
}

/**
* Configures the cache
*
* @param props Optionally can contain properties [reference-type=WEAK|SOFT|STRONG]
*/
public void setProperties(Properties props) {
String size = props.getProperty("cache-size");
if (size == null) {
size = props.getProperty("size");
}
if (size != null) {
cacheSize = Integer.parseInt(size);
}
}

/**
* Add an object to the cache
*
* @param cacheModel The cacheModel
* @param key The key of the object to be cached
* @param value The object to be cached
*/
public void putObject(CacheModel cacheModel, Object key, Object value) {
cache.put(key, value);
keyList.add(key);
//如果超过大小就删除头部元素
if (keyList.size() > cacheSize) {
try {
Object oldestKey = keyList.remove(0);
cache.remove(oldestKey);
} catch (IndexOutOfBoundsException e) {
//ignore
}
}
}

/**
* Get an object out of the cache.
*
* @param cacheModel The cache model
* @param key The key of the object to be returned
* @return The cached object (or null)
*/
public Object getObject(CacheModel cacheModel, Object key) {
return cache.get(key);
}

public Object removeObject(CacheModel cacheModel, Object key) {
keyList.remove(key);
return cache.remove(key);
}

/**
* Flushes the cache.
*
* @param cacheModel The cache model
*/
public void flush(CacheModel cacheModel) {
cache.clear();
keyList.clear();
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值