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