LRU Cache

看了下RU(Least Recently Used ,最近最少使用),可以使用LinkedHashMap实现,到是蛮简单的.LinkedHashMap会将get或是put的数据置于底端.
重写removeEldestEntry()可以设定根据size来调整cache的数量.

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * This class uses the LinkedHashMap to build LRU cache.
 * User can define the cache size. 
 */
public class LRUCache
{
	int cacheSize = 0;
	float loadFactor = 0.75f; //default
	LinkedHashMap map;
	
	public LRUCache(int cacheSize)
	{
		this.cacheSize = cacheSize;
		map = new LinkedHashMap(cacheSize, loadFactor, true)
		{
			protected boolean removeEldestEntry(Map.Entry eldest)
			{
				return size() > LRUCache.this.cacheSize;
				//return false;
			}
		};
	}

	public synchronized void clear()
	{
		map.clear();
	}

	public synchronized Object get(Object key)
	{
		return map.get(key);
	}

	public synchronized void put(Object key, Object value)
	{
		map.put(
			key,
			value);
	}
	
	public synchronized Object remove(Object key)
	{
		return map.remove(key);
	}

	public synchronized int size()
	{
		return map.size();
	}
	
	public synchronized Collection values()
	{
		return map.values();
	}
	
	public static void main(String []args)
	{
		// testing
		int size = 3;
		LRUCache cache = new LRUCache(size);
		cache.put(new Integer("1"), "1");
		cache.put(new Integer("2"), "2");
		cache.put(new Integer("3"), "3");
		
		String value = (String)cache.get(new Integer(1));
		System.out.println(value);
		System.out.println("Testing ...");

		Object[] values = cache.values().toArray();
		for (int i = 0; i < values.length; i++)
		{
			value = (String)values[i];
			System.out.println(value);
		}
	}
}

你可能感兴趣的:(java,cache)