import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.reflect.Field;
import java.util.Hashtable;
/**
* 简单的缓存工具
*
* @param <K> 缓存对象的主键
* @param <V> 缓存实例
*/
public class DataCache<K, V> {
private volatile static DataCache dataCache;
private Hashtable<K, DataReference> dataReferenceMap;
private ReferenceQueue<V> dataQueue;
private DataCache() {
dataReferenceMap = new Hashtable();
dataQueue = new ReferenceQueue();
}
private class DataReference extends SoftReference<V> {
private K key;
public DataReference(V data, String primaryKey) throws Exception {
super(data, dataQueue);
try {
Field field = data.getClass().getDeclaredField(primaryKey);
field.setAccessible(true);
key = (K) field.get(data);
}catch (Exception e){
throw e;
}
}
}
public static DataCache createCache() {
if (dataCache == null) {
synchronized (DataCache.class) {
if(dataCache == null){
dataCache = new DataCache();
}
}
}
return dataCache;
}
/**
* 向缓存中添加数据
*
* @param data 待缓存的实例
* @param primaryKeyName 实例对应数据库中的主键
*/
public void setCacheValue(V data, String primaryKeyName) throws Exception {
cleanCache();
DataReference dataReference = new DataReference(data, primaryKeyName);
dataReferenceMap.put(dataReference.key, dataReference);
}
/**
* 从缓存中取数据
*
* @return
*/
public V getCacheValue(K primaryKeyValue) {
V data = null;
if(dataReferenceMap.containsKey(primaryKeyValue)){
data = dataReferenceMap.get(primaryKeyValue).get();
}
return data;
}
private void cleanCache() {
DataReference ref = null;
while ((ref = (DataReference) dataQueue.poll()) != null) {
dataReferenceMap.remove(ref.key);
}
}
public void clearAll() {
cleanCache();
dataReferenceMap.clear();
System.gc();
System.runFinalization();
}
}
网友评论