1 3 package org.jmock.examples.timedcache; 4 5 import java.util.HashMap ; 6 7 8 public class TimedCache 9 { 10 private ObjectLoader loader; 11 private Clock clock; 12 private ReloadPolicy reloadPolicy; 13 private HashMap cachedValues = new HashMap (); 14 15 private class TimestampedValue 16 { 17 public final Object value; 18 public final Timestamp loadTime; 19 20 public TimestampedValue( final Object value, final Timestamp timestamp ) { 21 this.value = value; 22 this.loadTime = timestamp; 23 } 24 } 25 26 27 public TimedCache( ObjectLoader loader, Clock clock, ReloadPolicy reloadPolicy ) { 28 this.loader = loader; 29 this.clock = clock; 30 this.reloadPolicy = reloadPolicy; 31 } 32 33 public Object lookup( Object theKey ) { 34 TimestampedValue found = (TimestampedValue)cachedValues.get(theKey); 35 36 if (found == null || reloadPolicy.shouldReload(found.loadTime, clock.getCurrentTime())) { 37 found = loadObject(theKey); 38 } 39 return found.value; 40 } 41 42 private TimestampedValue loadObject( Object key ) { 43 Object value = loader.load(key); 44 TimestampedValue timestampedValue = new TimestampedValue(value, clock.getCurrentTime()); 45 46 cachedValues.put(key, timestampedValue); 47 48 return timestampedValue; 49 } 50 51 public void putValue( Object key, Object value, Timestamp loadTime ) { 52 cachedValues.put(key, new TimestampedValue(value, loadTime)); 53 54 } 55 } | Popular Tags |