1 18 package org.apache.batik.ext.awt.image.rendered; 19 20 import org.apache.batik.util.DoublyLinkedList; 21 22 public class LRUCache { 23 24 29 public interface LRUObj { 30 36 public void lruSet(LRUNode nde); 37 41 public LRUNode lruGet(); 42 45 public void lruRemove(); 46 } 47 48 52 public class LRUNode extends DoublyLinkedList.Node { 53 private LRUObj obj = null; 54 public LRUObj getObj () { return obj; } 55 protected void setObj (LRUObj newObj) { 56 if (obj != null) obj.lruRemove(); 57 58 obj = newObj; 59 if (obj != null) obj.lruSet(this); 60 } 61 } 62 63 private DoublyLinkedList free = null; 64 private DoublyLinkedList used = null; 65 private int maxSize = 0; 66 67 public LRUCache(int size) { 68 if (size <= 0) size=1; 69 maxSize = size; 70 71 free = new DoublyLinkedList(); 72 used = new DoublyLinkedList(); 73 74 while (size > 0) { 75 free.add(new LRUNode()); 76 size--; 77 } 78 } 79 80 public int getUsed() { 81 return used.getSize(); 82 } 83 84 public synchronized void setSize(int newSz) { 85 86 if (maxSize < newSz) { 88 for (int i=maxSize; i<newSz; i++) 89 free.add(new LRUNode()); 90 91 } else if (maxSize > newSz) { 92 93 for (int i=used.getSize(); i>newSz; i--) { 94 LRUNode nde = (LRUNode)used.getTail(); 95 used.remove(nde); 96 nde.setObj(null); 97 } 98 } 99 100 maxSize = newSz; 101 } 102 103 public synchronized void flush() { 104 while (used.getSize() > 0) { 105 LRUNode nde = (LRUNode)used.pop(); 106 nde.setObj(null); 107 free.add(nde); 108 } 109 } 110 111 public synchronized void remove(LRUObj obj) { 112 LRUNode nde = obj.lruGet(); 113 if (nde == null) return; 114 used.remove(nde); 115 nde.setObj(null); 116 free.add(nde); 117 } 118 119 public synchronized void touch(LRUObj obj) { 120 LRUNode nde = obj.lruGet(); 121 if (nde == null) return; 122 used.touch(nde); 123 } 124 125 public synchronized void add(LRUObj obj) { 126 LRUNode nde = obj.lruGet(); 127 128 if (nde != null) { 130 used.touch(nde); 131 return; 132 } 133 134 if (free.getSize() > 0) { 135 nde = (LRUNode)free.pop(); 136 nde.setObj(obj); 137 used.add(nde); 138 } else { 139 nde = (LRUNode)used.getTail(); 140 nde.setObj(obj); 141 used.touch(nde); 142 } 143 } 144 145 protected synchronized void print() { 146 System.out.println("In Use: " + used.getSize() + 147 " Free: " + free.getSize()); 148 LRUNode nde = (LRUNode)used.getHead(); 149 if (nde == null) return; 150 do { 151 System.out.println(nde.getObj()); 152 nde = (LRUNode)nde.getNext(); 153 } while (nde != used.getHead()); 154 } 155 156 } 157 | Popular Tags |