一、前言
关于jtds源码包中基于java.util.HashMap实现net.sourceforge.jtds.jdbc.cache.SimpleLRUCache简单(Least Recently Used)最近最少使用缓存算法,详情参见源码说明。
二、源码说明
package net.sourceforge.jtds.jdbc.cache;@b@@b@import java.util.HashMap;@b@import java.util.LinkedList;@b@@b@public class SimpleLRUCache extends HashMap@b@{@b@ private final int maxCacheSize;@b@ private final LinkedList list;@b@@b@ public SimpleLRUCache(int maxCacheSize)@b@ {@b@ super(maxCacheSize);@b@ this.maxCacheSize = Math.max(0, maxCacheSize);@b@ this.list = new LinkedList();@b@ }@b@@b@ public synchronized void clear()@b@ {@b@ super.clear();@b@ this.list.clear();@b@ }@b@@b@ public synchronized Object put(Object key, Object value)@b@ {@b@ if (this.maxCacheSize == 0) {@b@ return null;@b@ }@b@@b@ if ((!(super.containsKey(key))) && (!(this.list.isEmpty())) && (this.list.size() + 1 > this.maxCacheSize)) {@b@ Object deadKey = this.list.removeLast();@b@ super.remove(deadKey);@b@ }@b@@b@ freshenKey(key);@b@ return super.put(key, value);@b@ }@b@@b@ public synchronized Object get(Object key)@b@ {@b@ Object value = super.get(key);@b@ if (value != null)@b@ freshenKey(key);@b@@b@ return value;@b@ }@b@@b@ public synchronized Object remove(Object key)@b@ {@b@ this.list.remove(key);@b@ return super.remove(key);@b@ }@b@@b@ private void freshenKey(Object key)@b@ {@b@ this.list.remove(key);@b@ this.list.addFirst(key);@b@ }@b@}