1 18 package org.apache.activemq.memory; 19 20 import java.util.Iterator ; 21 import java.util.LinkedList ; 22 23 import org.apache.activemq.thread.Task; 24 import org.apache.activemq.thread.TaskRunner; 25 import org.apache.activemq.thread.TaskRunnerFactory; 26 import org.apache.commons.logging.Log; 27 import org.apache.commons.logging.LogFactory; 28 29 import java.util.concurrent.CopyOnWriteArrayList ; 30 31 public class CacheEvictionUsageListener implements UsageListener { 32 33 private final static Log log = LogFactory.getLog(CacheEvictionUsageListener.class); 34 35 private final CopyOnWriteArrayList evictors = new CopyOnWriteArrayList (); 36 private final int usageHighMark; 37 private final int usageLowMark; 38 39 private final TaskRunner evictionTask; 40 private final UsageManager usageManager; 41 42 public CacheEvictionUsageListener(UsageManager usageManager, int usageHighMark, int usageLowMark, TaskRunnerFactory taskRunnerFactory) { 43 this.usageManager = usageManager; 44 this.usageHighMark = usageHighMark; 45 this.usageLowMark = usageLowMark; 46 evictionTask = taskRunnerFactory.createTaskRunner(new Task(){ 47 public boolean iterate() { 48 return evictMessages(); 49 } 50 }, "Cache Evictor: "+System.identityHashCode(this)); 51 } 52 53 private boolean evictMessages() { 54 try { 56 log.debug("Evicting cache memory usage: "+usageManager.getPercentUsage()); 57 58 LinkedList list = new LinkedList (evictors); 59 while (list.size()>0 && usageManager.getPercentUsage() > usageLowMark) { 60 61 for (Iterator iter = list.iterator(); iter.hasNext();) { 63 CacheEvictor evictor = (CacheEvictor) iter.next(); 64 if( evictor.evictCacheEntry() == null ) 65 iter.remove(); 66 } 67 } 68 } finally { 69 } 70 return false; 71 } 72 73 public void onMemoryUseChanged(UsageManager memoryManager, int oldPercentUsage, int newPercentUsage) { 74 if (oldPercentUsage < newPercentUsage && memoryManager.getPercentUsage() >= usageHighMark) { 77 try { 78 evictionTask.wakeup(); 79 } catch (InterruptedException e) { 80 Thread.currentThread().interrupt(); 81 } 82 } 83 } 84 85 public void add(CacheEvictor evictor) { 86 evictors.add(evictor); 87 } 88 89 public void remove(CacheEvictor evictor) { 90 evictors.remove(evictor); 91 } 92 } 93 | Popular Tags |