(转)超简单的缓存实现

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 15:47   3476   0

(转)超简单的缓存实现

基于ConcurrentHashMap和WeakHashMap的简单缓存实现
 
package test;
 
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
 
public final class SimpleCache<K,V> {
 
    private final Lock lock = new ReentrantLock();
    private final int maxCapacity;
    private final Map<K,V> eden;
    private final Map<K,V> longterm;
 
    public SimpleCache(int maxCapacity) {
        this.maxCapacity = maxCapacity;
        this.eden = new ConcurrentHashMap<K,V>(maxCapacity);
        this.longterm = new WeakHashMap<K,V>(maxCapacity);
    }
 
    public V get(K k) {
        V v = this.eden.get(k);
        if (v == null) {
            lock.lock();
            try{
                v = this.longterm.get(k);
            }finally{
                lock.unlock();
            }
            if (v != null) {
                this.eden.put(k, v);
            }
        }
        return v;
    }
 
    public void put(K k, V v) {
        if (this.eden.size() >= maxCapacity) {
            lock.lock();
            try{
                this.longterm.putAll(this.eden);
            }finally{
                lock.unlock();
            }
            this.eden.clear();
        }
        this.eden.put(k, v);
    }
}

  

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP