/[projects]/android/TrainInfo/src/dk/thoerup/traininfo/util/AndroidTimeoutCache.java
ViewVC logotype

Annotation of /android/TrainInfo/src/dk/thoerup/traininfo/util/AndroidTimeoutCache.java

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1027 - (hide annotations) (download)
Wed Sep 8 06:03:45 2010 UTC (13 years, 8 months ago) by torben
File size: 1151 byte(s)
Clean up the cache to avoid OutOfMemoryError exceptions
1 torben 390 package dk.thoerup.traininfo.util;
2    
3     import java.util.HashMap;
4    
5    
6     public class AndroidTimeoutCache<K,V> {
7    
8     class CacheItem<T> {
9    
10     public CacheItem(T v) {
11     value = v;
12     lastupdate = android.os.SystemClock.elapsedRealtime();
13     }
14    
15     public long lastupdate;
16     public T value;
17     }
18    
19     private HashMap<K,CacheItem<V>> cache = new HashMap<K,CacheItem<V>>();
20     private long timeout;
21    
22     public AndroidTimeoutCache(int timeout) {
23     this.timeout = timeout;
24     }
25    
26 torben 1027 public void purgeOldEntries() {
27    
28     long now = android.os.SystemClock.elapsedRealtime();
29    
30     for (K key : cache.keySet()) {
31     CacheItem<V> item = cache.get(key);
32     if ( (item.lastupdate+timeout) < now) { //item too old
33     cache.remove(key);
34     }
35     }
36     }
37    
38 torben 390 public void put(K k, V v) {
39     CacheItem<V> item= new CacheItem<V>(v);
40     cache.put(k, item);
41     }
42    
43     public V get(K k) {
44     long now = android.os.SystemClock.elapsedRealtime();
45    
46     CacheItem<V> item = cache.get(k);
47    
48    
49     if (item != null) {
50     if ( (item.lastupdate+timeout) < now) { //item too old
51     return null;
52     } else {
53     return item.value; //item still good
54     }
55     } else {
56     return null; // no item found
57     }
58    
59     }
60    
61     }

  ViewVC Help
Powered by ViewVC 1.1.20