1 5 6 7 14 15 package org.joseki.util.cache; 16 17 import java.util.* ; 18 import org.apache.commons.logging.*; 19 20 public class Cache 21 { 22 static Log log = LogFactory.getLog(Cache.class.getName()) ; 23 24 Map objects = new HashMap() ; 25 CacheItemFactory factory = null ; 26 CachePolicy policy = null ; 27 int size ; 28 29 public Cache(int _size, CacheItemFactory _factory, CachePolicy _policy) 30 { 31 factory = _factory ; 32 policy = _policy ; 33 size = _size ; 34 } 35 36 public synchronized void remove(Object key) 37 { 38 objects.remove(key) ; 39 } 40 41 public synchronized void put(Object key, Object obj) 42 { 43 if ( objects.size() >= size ) 44 expel(1) ; 45 46 policy.newItem(key, obj) ; 47 objects.put(key, obj) ; 48 } 49 50 public synchronized Object get(Object key) 51 { 52 log.trace("get("+key+")") ; 53 Object obj = objects.get(key) ; 54 if ( obj == null ) 55 { 56 if ( objects.size() >= size ) 57 expel(1) ; 58 59 obj = factory.create(key) ; 60 if ( obj == null ) 61 log.warn("factory.create("+key+") returned null") ; 62 63 put(key, obj) ; 64 } 65 policy.update(key) ; 66 return obj ; 67 } 68 69 private void expel(int count) 70 { 71 Object [] keys = policy.expel(count) ; 72 for ( int i = 0 ; i < keys.length ; i++ ) 73 { 74 Object obj = objects.remove(keys[i]) ; 75 factory.destroy(keys[i], obj) ; 76 } 77 } 78 } 79 80 81 107 | Popular Tags |