FileDocCategorySizeDatePackage
LRUCache.javaAPI DocGlassfish v2 API4734Fri May 04 22:33:14 BST 2007org.apache.tomcat.util.collections

LRUCache

public class LRUCache extends Object
This class implements a Generic LRU Cache
author
Ignacio J. Ortega

Fields Summary
private int
cacheSize
private Hashtable
nodes
private int
currentSize
private CacheNode
first
private CacheNode
last
Constructors Summary
public LRUCache(int i)

        currentSize = 0;
        cacheSize = i;
        nodes = new Hashtable(i);
    
Methods Summary
public voidclear()

        first = null;
        last = null;
    
public java.lang.Objectget(java.lang.Object key)

        CacheNode node = (CacheNode)nodes.get(key);
        if(node != null)
        {
            moveToHead(node);
            return node.value;
        }
        else
        {
            return null;
        }
    
private voidmoveToHead(org.apache.tomcat.util.collections.LRUCache$CacheNode node)

        if(node == first)
            return;
        if(node.prev != null)
            node.prev.next = node.next;
        if(node.next != null)
            node.next.prev = node.prev;
        if(last == node)
            last = node.prev;
        if(first != null)
        {
            node.next = first;
            first.prev = node;
        }
        first = node;
        node.prev = null;
        if(last == null)
            last = first;
    
public voidput(java.lang.Object key, java.lang.Object value)

        CacheNode node = (CacheNode)nodes.get(key);
        if(node == null)
        {
            if(currentSize >= cacheSize)
            {
                if(last != null)
                    nodes.remove(last.key);
                removeLast();
            }
            else
            {
                currentSize++;
            }
            node = new CacheNode();
        }
        node.value = value;
        node.key = key;
        moveToHead(node);
        nodes.put(key, node);
    
public java.lang.Objectremove(java.lang.Object key)

        CacheNode node = (CacheNode)nodes.get(key);
        if (node != null) {
            if (node.prev != null) {
                node.prev.next = node.next;
            }
            if (node.next != null) {
                node.next.prev = node.prev;
            }
            if (last == node)
                last = node.prev;
            if (first == node)
                first = node.next;
        }
        return node;
    
private voidremoveLast()

        if(last != null)
        {
            if(last.prev != null)
                last.prev.next = null;
            else
                first = null;
            last = last.prev;
        }