KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > jodd > cache > TimedCache


1 // Copyright (c) 2003-2007, Jodd Team (jodd.sf.net). All Rights Reserved.
2

3 package jodd.cache;
4
5 import java.util.HashMap JavaDoc;
6 import java.util.Iterator JavaDoc;
7 import java.util.Timer JavaDoc;
8 import java.util.TimerTask JavaDoc;
9
10 /**
11  * Timed cache. Not limited by size, objects are removed only when they are expired.
12  * Prune is not invoked explicitly by standard {@link Cache} methods, however,
13  * it is possible to schedule prunes on fined-rate delays.
14  */

15 public class TimedCache extends AbstractCacheMap {
16
17     public TimedCache(long timeout) {
18         this.cacheSize = 0;
19         this.timeout = timeout;
20         cacheMap = new HashMap JavaDoc();
21     }
22
23     // ---------------------------------------------------------------- prune
24

25     /**
26      * Prunes expired elements from the cache. Returns the number of removed objects.
27      */

28     public synchronized int prune() {
29         int count = 0;
30         Iterator JavaDoc values = cacheMap.values().iterator();
31         while (values.hasNext()) {
32             CacheObject co = (CacheObject) values.next();
33             if (co.isExpired() == true) {
34                 values.remove();
35                 count++;
36             }
37         }
38         return count;
39     }
40
41
42     // ---------------------------------------------------------------- autoprune
43

44     protected Timer JavaDoc pruneTimer;
45
46     /**
47      * Schedules prune.
48      */

49     public void schedulePrune(long delay) {
50         if (pruneTimer != null) {
51             pruneTimer.cancel();
52         }
53         pruneTimer = new Timer JavaDoc();
54         pruneTimer.schedule(
55                 new TimerTask JavaDoc() {
56                     public void run() {
57                         prune();
58                     }
59                 }, delay, delay
60         );
61     }
62
63     /**
64      * Cancels prune schedules.
65      */

66     public void cancelPruneSchedule() {
67         if (pruneTimer != null) {
68             pruneTimer.cancel();
69             pruneTimer = null;
70         }
71     }
72
73 }
74
Popular Tags