1 17 18 package com.whirlycott.cache.policy; 19 20 import java.util.ArrayList ; 21 import java.util.Collections ; 22 import java.util.Iterator ; 23 import java.util.List ; 24 import java.util.Map ; 25 import java.util.Map.Entry; 26 27 import org.apache.commons.logging.Log; 28 import org.apache.commons.logging.LogFactory; 29 30 import EDU.oswego.cs.dl.util.concurrent.ConcurrentHashMap; 31 32 import com.whirlycott.cache.CacheConfiguration; 33 import com.whirlycott.cache.CacheMaintenancePolicy; 34 import com.whirlycott.cache.ManagedCache; 35 import com.whirlycott.cache.Messages; 36 37 43 public class LFUMaintenancePolicy implements CacheMaintenancePolicy { 44 45 private static final Log log = LogFactory.getLog( LFUMaintenancePolicy.class ); 46 47 protected ManagedCache managedCache = null; 48 49 protected int maxSize; 50 51 public void performMaintenance() { 52 if( log.isDebugEnabled() ) { 53 log.debug( Messages.getString("LFUMaintenancePolicy.performing_lfu_maintenance") ); 55 final Object [] args = { 56 new Integer (maxSize), 57 new Integer (managedCache.size()) 58 }; 59 log.debug( Messages.getCompoundString("CacheMaintenancePolicy.report_items", args) ); } 61 62 int currentSize = managedCache.size(); 64 if ( maxSize < currentSize ) { 65 if( log.isDebugEnabled() ) { 66 final Object [] args1 = { 67 new Integer (currentSize - maxSize) 68 }; 69 log.debug( Messages.getCompoundString("CacheMaintenancePolicy.clearing_approximately", args1) ); } 71 final List entries = new ArrayList ( new ConcurrentHashMap( managedCache ).entrySet() ); 72 Collections.sort( entries, new CountComparator() ); 73 final List removeThese = entries.subList( 0, currentSize - maxSize ); 74 for (final Iterator i = removeThese.iterator(); i.hasNext();) { 75 final Map.Entry entry = (Entry) i.next(); 76 if (entry != null) { 77 managedCache.remove( entry.getKey() ); 82 } 83 } 84 if( log.isDebugEnabled() ) 85 log.debug( Messages.getString("LFUMaintenancePolicy.new_size") + managedCache.size() ); } 87 } 88 89 public void setCache(final ManagedCache _cache) { 90 managedCache = _cache; 91 } 92 93 public void setConfiguration(final CacheConfiguration _configuration) { 94 maxSize = _configuration.getMaxSize(); 95 } 96 }
| Popular Tags
|