1 |
package dk.thoerup.traininfo.util; |
package dk.thoerup.traininfo.util; |
2 |
|
|
3 |
import java.util.HashMap; |
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> { |
public class AndroidTimeoutCache<K,V> { |
16 |
lastupdate = android.os.SystemClock.elapsedRealtime(); |
lastupdate = android.os.SystemClock.elapsedRealtime(); |
17 |
} |
} |
18 |
|
|
19 |
|
public boolean isExpired(long now) { |
20 |
|
return ( (lastupdate+timeout) < now); |
21 |
|
} |
22 |
|
|
23 |
public long lastupdate; |
public long lastupdate; |
24 |
public T value; |
public T value; |
25 |
} |
} |
34 |
public void purgeOldEntries() { |
public void purgeOldEntries() { |
35 |
|
|
36 |
long now = android.os.SystemClock.elapsedRealtime(); |
long now = android.os.SystemClock.elapsedRealtime(); |
37 |
|
//Log.e("Purge","Purge"); |
38 |
|
|
39 |
for (K key : cache.keySet()) { |
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); |
CacheItem<V> item = cache.get(key); |
45 |
if ( (item.lastupdate+timeout) < now) { //item too old |
if ( item.isExpired(now)) { //item too old |
46 |
cache.remove(key); |
it.remove(); |
47 |
} |
//Log.e("Purge", "removing"); |
48 |
} |
} |
49 |
|
} |
50 |
|
|
51 |
} |
} |
52 |
|
|
53 |
public void put(K k, V v) { |
public void put(K k, V v) { |
62 |
|
|
63 |
|
|
64 |
if (item != null) { |
if (item != null) { |
65 |
if ( (item.lastupdate+timeout) < now) { //item too old |
if ( item.isExpired(now) ) { //item too old |
66 |
return null; |
return null; |
67 |
} else { |
} else { |
68 |
return item.value; //item still good |
return item.value; //item still good |