1 16 package org.apache.commons.collections.list; 17 18 import java.io.IOException ; 19 import java.io.ObjectInputStream ; 20 import java.io.ObjectOutputStream ; 21 import java.io.Serializable ; 22 import java.util.Collection ; 23 24 46 public class NodeCachingLinkedList extends AbstractLinkedList implements Serializable { 47 48 49 static final long serialVersionUID = 6897789178562232073L; 50 51 54 protected static final int DEFAULT_MAXIMUM_CACHE_SIZE = 20; 55 56 61 protected transient Node firstCachedNode; 62 63 66 protected transient int cacheSize; 67 68 71 protected int maximumCacheSize; 72 73 77 public NodeCachingLinkedList() { 78 this(DEFAULT_MAXIMUM_CACHE_SIZE); 79 } 80 81 86 public NodeCachingLinkedList(Collection coll) { 87 super(coll); 88 this.maximumCacheSize = DEFAULT_MAXIMUM_CACHE_SIZE; 89 } 90 91 96 public NodeCachingLinkedList(int maximumCacheSize) { 97 super(); 98 this.maximumCacheSize = maximumCacheSize; 99 init(); } 101 102 108 protected int getMaximumCacheSize() { 109 return maximumCacheSize; 110 } 111 112 117 protected void setMaximumCacheSize(int maximumCacheSize) { 118 this.maximumCacheSize = maximumCacheSize; 119 shrinkCacheToMaximumSize(); 120 } 121 122 125 protected void shrinkCacheToMaximumSize() { 126 while (cacheSize > maximumCacheSize) { 128 getNodeFromCache(); 129 } 130 } 131 132 139 protected Node getNodeFromCache() { 140 if (cacheSize == 0) { 141 return null; 142 } 143 Node cachedNode = firstCachedNode; 144 firstCachedNode = cachedNode.next; 145 cachedNode.next = null; cacheSize--; 148 return cachedNode; 149 } 150 151 156 protected boolean isCacheFull() { 157 return cacheSize >= maximumCacheSize; 158 } 159 160 166 protected void addNodeToCache(Node node) { 167 if (isCacheFull()) { 168 return; 170 } 171 Node nextCachedNode = firstCachedNode; 173 node.previous = null; 174 node.next = nextCachedNode; 175 node.setValue(null); 176 firstCachedNode = node; 177 cacheSize++; 178 } 179 180 188 protected Node createNode(Object value) { 189 Node cachedNode = getNodeFromCache(); 190 if (cachedNode == null) { 191 return super.createNode(value); 192 } else { 193 cachedNode.setValue(value); 194 return cachedNode; 195 } 196 } 197 198 204 protected void removeNode(Node node) { 205 super.removeNode(node); 206 addNodeToCache(node); 207 } 208 209 214 protected void removeAllNodes() { 215 int numberOfNodesToCache = Math.min(size, maximumCacheSize - cacheSize); 220 Node node = header.next; 221 for (int currentIndex = 0; currentIndex < numberOfNodesToCache; currentIndex++) { 222 Node oldNode = node; 223 node = node.next; 224 addNodeToCache(oldNode); 225 } 226 super.removeAllNodes(); 227 } 228 229 233 private void writeObject(ObjectOutputStream out) throws IOException { 234 out.defaultWriteObject(); 235 doWriteObject(out); 236 } 237 238 241 private void readObject(ObjectInputStream in) throws IOException , ClassNotFoundException { 242 in.defaultReadObject(); 243 doReadObject(in); 244 } 245 246 } 247 | Popular Tags |