dubbo --- LRUCache简单实现

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

public class LRUCache extends LinkedHashMap {

	private static final long serialVersionUID = -5167631809472116969L;

	private static final float DEFAULT_LOAD_FACTOR = 0.75f;

	private static final int DEFAULT_MAX_CAPACITY = 1000;

	private volatile int maxCapacity;

	private final Lock lock = new ReentrantLock();

    public LRUCache() {
    	this(DEFAULT_MAX_CAPACITY);
    }

    public LRUCache(int maxCapacity) {
        super(16, DEFAULT_LOAD_FACTOR, true);
        this.maxCapacity = maxCapacity;
    }

    @Override
    protected boolean removeEldestEntry(java.util.Map.Entry eldest) {
        return size() > maxCapacity;
    }

    @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
    public V put(K key, V value) {
        try {
            lock.lock();
            return super.put(key, value);
        } finally {
            lock.unlock();
        }
    }

    @Override
    public V remove(Object key) {
        try {
            lock.lock();
            return super.remove(key);
        } finally {
            lock.unlock();
        }
    }

    @Override
    public int size() {
        try {
            lock.lock();
            return super.size();
        } finally {
            lock.unlock();
        }
    }

    @Override
    public void clear() {
        try {
            lock.lock();
            super.clear();
        } finally {
            lock.unlock();
        }
    }

	public int getMaxCapacity() {
		return maxCapacity;
	}

	public void setMaxCapacity(int maxCapacity) {
		this.maxCapacity = maxCapacity;
	}

}

 

利用LinkedHashMap扩展实现简单的LRUCache,主要两点:

1.重写removeEldestEntry方法,决定何时移除最旧条目

2.关键方法加锁,如put、get

 

 

说明:

加载因子:

 

如果哈希表中的元素放得太满,就必须进行rehashing(再哈希)。再哈希使哈希表元数增倍,
并将原有的对象重新导入新的哈希表元中,而原始的哈希表元被删除。
load factor(加载因子)决定何时要对哈希表进行再哈希。
在Java编程语言中,加载因子默认值为0.75,默认哈希表元为101

 

你可能感兴趣的:(dubbo)