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 |
torben |
1033 |
public boolean isExpired(long now) { |
20 |
|
|
return ( (lastupdate+timeout) < now); |
21 |
|
|
} |
22 |
|
|
|
23 |
torben |
390 |
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 |
torben |
1027 |
public void purgeOldEntries() { |
35 |
|
|
|
36 |
|
|
long now = android.os.SystemClock.elapsedRealtime(); |
37 |
torben |
1032 |
//Log.e("Purge","Purge"); |
38 |
torben |
1027 |
|
39 |
torben |
1032 |
Set<K> keyset = cache.keySet(); |
40 |
|
|
|
41 |
|
|
for ( Iterator<K> it = keyset.iterator(); it.hasNext() ;) { |
42 |
|
|
K key = it.next(); |
43 |
|
|
|
44 |
torben |
1027 |
CacheItem<V> item = cache.get(key); |
45 |
torben |
1033 |
if ( item.isExpired(now)) { //item too old |
46 |
torben |
1032 |
it.remove(); |
47 |
|
|
//Log.e("Purge", "removing"); |
48 |
|
|
} |
49 |
|
|
} |
50 |
|
|
|
51 |
torben |
1027 |
} |
52 |
|
|
|
53 |
torben |
390 |
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 |
torben |
1033 |
if ( item.isExpired(now) ) { //item too old |
66 |
torben |
390 |
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 |
|
|
} |