KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jmock > examples > timedcache > TimedCache


1 /* Copyright (c) 2000-2004 jMock.org
2  */

3 package org.jmock.examples.timedcache;
4
5 import java.util.HashMap JavaDoc;
6
7
8 public class TimedCache
9 {
10     private ObjectLoader loader;
11     private Clock clock;
12     private ReloadPolicy reloadPolicy;
13     private HashMap JavaDoc cachedValues = new HashMap JavaDoc();
14
15     private class TimestampedValue
16     {
17         public final Object JavaDoc value;
18         public final Timestamp loadTime;
19
20         public TimestampedValue( final Object JavaDoc 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 JavaDoc lookup( Object JavaDoc 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 JavaDoc key ) {
43         Object JavaDoc 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 JavaDoc key, Object JavaDoc value, Timestamp loadTime ) {
52         cachedValues.put(key, new TimestampedValue(value, loadTime));
53
54     }
55 }
Popular Tags