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 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 |
public void purgeOldEntries() { |
31 |
|
32 |
long now = android.os.SystemClock.elapsedRealtime(); |
33 |
//Log.e("Purge","Purge"); |
34 |
|
35 |
Set<K> keyset = cache.keySet(); |
36 |
|
37 |
for ( Iterator<K> it = keyset.iterator(); it.hasNext() ;) { |
38 |
K key = it.next(); |
39 |
|
40 |
CacheItem<V> item = cache.get(key); |
41 |
if ( (item.lastupdate+timeout) < now) { //item too old |
42 |
it.remove(); |
43 |
//Log.e("Purge", "removing"); |
44 |
} |
45 |
} |
46 |
|
47 |
} |
48 |
|
49 |
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 |
} |