/[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 1032 - (hide annotations) (download)
Wed Sep 8 09:29:42 2010 UTC (13 years, 8 months ago) by torben
File size: 1381 byte(s)
Fix the purgeOld methods ... the previous implementation could throw an exception :(

Do a versionCode bump to 32->33
1 torben 390 package dk.thoerup.traininfo.util;
2    
3     import java.util.HashMap;
4 torben 1032 import java.util.Iterator;
5     import java.util.Set;
6 torben 390
7 torben 1032 import android.util.Log;
8 torben 390
9 torben 1032
10 torben 390 public class AndroidTimeoutCache<K,V> {
11    
12     class CacheItem<T> {
13    
14     public CacheItem(T v) {
15     value = v;
16     lastupdate = android.os.SystemClock.elapsedRealtime();
17     }
18    
19     public long lastupdate;
20     public T value;
21     }
22    
23     private HashMap<K,CacheItem<V>> cache = new HashMap<K,CacheItem<V>>();
24     private long timeout;
25    
26     public AndroidTimeoutCache(int timeout) {
27     this.timeout = timeout;
28     }
29    
30 torben 1027 public void purgeOldEntries() {
31    
32     long now = android.os.SystemClock.elapsedRealtime();
33 torben 1032 //Log.e("Purge","Purge");
34 torben 1027
35 torben 1032 Set<K> keyset = cache.keySet();
36    
37     for ( Iterator<K> it = keyset.iterator(); it.hasNext() ;) {
38     K key = it.next();
39    
40 torben 1027 CacheItem<V> item = cache.get(key);
41     if ( (item.lastupdate+timeout) < now) { //item too old
42 torben 1032 it.remove();
43     //Log.e("Purge", "removing");
44     }
45     }
46    
47 torben 1027 }
48    
49 torben 390 public void put(K k, V v) {
50     CacheItem<V> item= new CacheItem<V>(v);
51     cache.put(k, item);
52     }
53    
54     public V get(K k) {
55     long now = android.os.SystemClock.elapsedRealtime();
56    
57     CacheItem<V> item = cache.get(k);
58    
59    
60     if (item != null) {
61     if ( (item.lastupdate+timeout) < now) { //item too old
62     return null;
63     } else {
64     return item.value; //item still good
65     }
66     } else {
67     return null; // no item found
68     }
69    
70     }
71    
72     }

  ViewVC Help
Powered by ViewVC 1.1.20