• lru缓存测试类


    package demo.mytest;

    import java.io.Serializable;
    import java.util.LinkedHashMap;
    import java.util.concurrent.locks.Lock;
    import java.util.concurrent.locks.ReentrantLock;

    public class LRUCache<K,V> extends LinkedHashMap<K, V> implements Serializable {
    /**
    * 缓存默认大小
    */
    public static final int DEFAULT_CAPASITY = 20;
    /**
    * 缓存实际大小
    */
    public static int CACHE_CAPASITY = DEFAULT_CAPASITY;
    /**
    * 线程同步锁
    */
    private static final Lock lock=new ReentrantLock();
    public LRUCache(){
    super(DEFAULT_CAPASITY);
    CACHE_CAPASITY = DEFAULT_CAPASITY;
    }
    public LRUCache(int size){
    super(size);
    CACHE_CAPASITY=size;
    }
    /**
    * 清理缓存.
    */
    @Override
    public void clear() {
    try{
    lock.lock();
    super.clear();
    }finally{
    lock.unlock();
    }

    }
    /**
    * 是否包含
    */
    @Override
    public boolean containsKey(Object key) {
    try{
    lock.lock();
    return super.containsKey(key);
    }finally{
    lock.unlock();
    }
    }
    /**
    * 获取缓存对象.
    */
    @Override
    public V get(Object key) {
    try{
    lock.lock();
    return super.get(key);
    }finally{
    lock.unlock();
    }
    }
    /*
    * 是否删除最早未使用缓存对象
    *
    */
    @Override
    protected boolean removeEldestEntry(java.util.Map.Entry<K, V> eldest) {
    try {
    lock.lock();
    return this.size() > CACHE_CAPASITY;
    } finally {
    lock.unlock();
    }
    }
    /*
    * 判断缓存是否为空
    *
    * @see java.util.HashMap#isEmpty()
    */
    @Override
    public boolean isEmpty() {
    try {
    lock.lock();
    return super.isEmpty();
    } finally {
    lock.unlock();
    }
    }
    /*
    * 放入缓存
    *
    * @see java.util.HashMap#put(java.lang.Object, java.lang.Object)
    */
    @Override
    public V put(K key, V value) {
    try {
    lock.lock();
    return super.put(key, value);
    } finally {
    lock.unlock();
    }
    }
    /*
    * 从缓存中删除
    *
    * @see java.util.HashMap#remove(java.lang.Object)
    */
    @Override
    public V remove(Object key) {
    try {
    lock.lock();
    return super.remove(key);
    } finally {
    lock.unlock();
    }
    }
    /*
    * 缓存大小
    *
    * @see java.util.HashMap#size()
    */
    @Override
    public int size() {
    try {
    lock.lock();
    return super.size();
    } finally {
    lock.unlock();
    }
    }
    }

  • 相关阅读:
    android手机上的app输入法遮挡输入框问题
    简单的百度地图使用
    简单的加入购物车动画效果,需引入外部js文件
    vue项目中axios跨域设置
    一次讲清promise
    js中宏任务,微任务,异步,同步,执行的顺序
    vantUI <van-uploader> 上传图片,如何获取图片的尺寸
    Vue双向绑定原理 从vue2的Object.defineProperty到vue3的proxy
    微信浏览器h5页面开发遇到问题
    Web前端优化最佳实践及工具集锦
  • 原文地址:https://www.cnblogs.com/likeju/p/5090763.html
Copyright © 2020-2023  润新知