You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
116 lines
2.9 KiB
116 lines
2.9 KiB
import java.util.*;
|
|
import java.util.concurrent.locks.ReentrantReadWriteLock;
|
|
|
|
|
|
public class Cache<K, V> {
|
|
private final Map<K, V> store;
|
|
private final int maxCapacity;
|
|
private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
|
|
|
|
|
|
public Cache(int maxCapacity) {
|
|
if (maxCapacity <= 0) {
|
|
throw new IllegalArgumentException("最大容量应为正数");
|
|
}
|
|
this.maxCapacity = maxCapacity;
|
|
this.store = new LinkedHashMap<K, V>(16, 0.75f, true) {
|
|
@Override
|
|
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
|
|
return size() > maxCapacity;
|
|
}
|
|
};
|
|
}
|
|
|
|
public V put(K key, V value) {
|
|
lock.writeLock().lock();
|
|
try {
|
|
return store.put(key, value);
|
|
} finally {
|
|
lock.writeLock().unlock();
|
|
}
|
|
}
|
|
|
|
public V get(K key) {
|
|
lock.readLock().lock();
|
|
try {
|
|
return store.get(key);
|
|
} finally {
|
|
lock.readLock().unlock();
|
|
}
|
|
}
|
|
|
|
public V remove(K key) {
|
|
lock.writeLock().lock();
|
|
try {
|
|
return store.remove(key);
|
|
} finally {
|
|
lock.writeLock().unlock();
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 清空所有缓存。
|
|
*/
|
|
public void clear() {
|
|
lock.writeLock().lock();
|
|
try {
|
|
store.clear();
|
|
} finally {
|
|
lock.writeLock().unlock();
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 当前缓存中的条目数。
|
|
*/
|
|
public int size() {
|
|
lock.readLock().lock();
|
|
try {
|
|
return store.size();
|
|
} finally {
|
|
lock.readLock().unlock();
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 判断是否包含某个键。
|
|
*/
|
|
public boolean containsKey(K key) {
|
|
lock.readLock().lock();
|
|
try {
|
|
return store.containsKey(key);
|
|
} finally {
|
|
lock.readLock().unlock();
|
|
}
|
|
}
|
|
|
|
@Override
|
|
public String toString() {
|
|
lock.readLock().lock();
|
|
try {
|
|
return store.toString();
|
|
} finally {
|
|
lock.readLock().unlock();
|
|
}
|
|
}
|
|
|
|
// ---------- 测试示例 ----------
|
|
public static void main(String[] args){
|
|
Cache<String,Integer> hc1 = new Cache<String,Integer>(3);
|
|
|
|
hc1.put("a",10);
|
|
hc1.put("b",6);
|
|
hc1.put("c",3);
|
|
|
|
System.out.println("b的值为" + hc1.get("b"));
|
|
System.out.println("a的值为" + hc1.get("a"));
|
|
System.out.println("缓存1的条目数(键值对数)为" + hc1.size());
|
|
|
|
hc1.remove("b");
|
|
System.out.println("删去b后,缓存1的条目数(键值对数)为" + hc1.size());
|
|
System.out.println("键中是否含有b:" + hc1.containsKey("b"));
|
|
|
|
hc1.clear();
|
|
System.out.println("清空缓存1后,缓存1的条目数(键值对数)为" + hc1.size());
|
|
}
|
|
}
|