1 5 package com.opensymphony.oscache.base.algorithm; 6 7 import org.apache.commons.logging.Log; 8 import org.apache.commons.logging.LogFactory; 9 10 import java.util.*; 11 12 31 public class LRUCache extends AbstractConcurrentReadCache { 32 33 private static final Log log = LogFactory.getLog(LRUCache.class); 34 35 38 private Collection list = new LinkedHashSet(); 39 40 43 private volatile boolean removeInProgress = false; 44 45 48 public LRUCache() { 49 super(); 50 } 51 52 57 public LRUCache(int capacity) { 58 this(); 59 maxEntries = capacity; 60 } 61 62 68 protected void itemRetrieved(Object key) { 69 while (removeInProgress) { 71 try { 72 Thread.sleep(5); 73 } catch (InterruptedException ie) { 74 } 75 } 76 77 synchronized (list) { 80 list.remove(key); 81 list.add(key); 82 } 83 } 84 85 91 protected void itemPut(Object key) { 92 synchronized (list) { list.remove(key); 95 list.add(key); 96 } 97 } 98 99 106 protected Object removeItem() { 107 Object toRemove = null; 108 109 removeInProgress = true; 110 try { 111 while (toRemove == null) { 112 try { 113 toRemove = removeFirst(); 114 } catch (Exception e) { 115 do { 120 try { 121 Thread.sleep(5); 122 } catch (InterruptedException ie) { 123 } 124 } while (list.isEmpty()); 125 } 126 } 127 } finally { 128 removeInProgress = false; 129 } 130 131 return toRemove; 132 } 133 134 139 protected void itemRemoved(Object key) { 140 list.remove(key); 141 } 142 143 148 private Object removeFirst() { 149 Object toRemove = null; 150 151 synchronized (list) { Iterator it = list.iterator(); 153 toRemove = it.next(); 154 it.remove(); 155 } 156 157 return toRemove; 158 } 159 } 160 | Popular Tags |