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