001: package org.shiftone.cache.policy.fifo;
002:
003: import org.shiftone.cache.util.*;
004: import org.shiftone.cache.util.reaper.ReapableCache;
005:
006: import java.util.Map;
007:
008: /**
009: * Class FifoCache
010: *
011: *
012: * @author <a href="mailto:jeff@shiftone.org">Jeff Drost</a>
013: * @version $Revision: 1.7 $
014: */
015: class FifoCache extends AbstractPolicyCache implements ReapableCache {
016:
017: private static final Log LOG = new Log(FifoCache.class);
018: private final Map map;
019: private final LinkedList fifo;
020:
021: FifoCache(String name, long timeoutMilliSeconds, int maxSize) {
022:
023: super (name, timeoutMilliSeconds, maxSize);
024:
025: this .map = MapFactory.createMap(maxSize);
026: this .fifo = new LinkedList();
027: }
028:
029: protected CacheNode findNodeByKey(Object key) {
030: return (FifoNode) map.get(key);
031: }
032:
033: public int size() {
034: return map.size();
035: }
036:
037: /**
038: * <b>DO NOTHING</b>
039: */
040: protected final void revalueNode(CacheNode cacheNode) {
041: }
042:
043: protected void delete(CacheNode node) {
044:
045: FifoNode n = (FifoNode) node;
046:
047: fifo.remove(n.fifoNode);
048: map.remove(n.key);
049: }
050:
051: protected void removeLeastValuableNode() {
052:
053: LinkedListNode lln = null;
054: FifoNode node = null;
055:
056: lln = fifo.peekLast();
057: node = (FifoNode) lln.getValue();
058:
059: delete(node);
060: }
061:
062: public void removeExpiredElements() {
063:
064: LinkedListNode lln = null;
065: CacheNode node;
066:
067: while ((lln = fifo.peekLast()) != null) {
068: node = (CacheNode) lln.getValue();
069:
070: if (node.isExpired()) {
071: delete(node);
072: } else {
073:
074: // not expired.. can stop now
075: break;
076: }
077: }
078: }
079:
080: protected CacheNode createNode(Object userKey, Object cacheObject) {
081:
082: FifoNode node = null;
083:
084: node = new FifoNode();
085: node.key = userKey;
086: node.value = cacheObject;
087: node.fifoNode = fifo.addFirst(node); // expensive
088: node.timeoutTime = System.currentTimeMillis()
089: + getTimeoutMilliSeconds();
090:
091: map.put(userKey, node);
092:
093: return node;
094: }
095:
096: String dumpFifoKeys() {
097:
098: String dump = null;
099: StringBuffer sb = new StringBuffer();
100: LinkedListNode node = fifo.peekFirst();
101: FifoNode current = null;
102:
103: while (node != null) {
104: current = (FifoNode) node.getValue();
105:
106: sb.append(current.key);
107:
108: node = node.getNext();
109: }
110:
111: dump = sb.toString();
112:
113: return dump;
114: }
115: }
|