/[projects]/android/TrainInfo/src/dk/thoerup/traininfo/util/AndroidTimeoutCache.java
ViewVC logotype

Annotation of /android/TrainInfo/src/dk/thoerup/traininfo/util/AndroidTimeoutCache.java

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1551 - (hide annotations) (download)
Thu Jul 7 20:45:17 2011 UTC (12 years, 11 months ago) by torben
File size: 1420 byte(s)
Minor cleanups (imports etc)
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    
8 torben 1032
9 torben 390 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 torben 1033 public boolean isExpired(long now) {
19     return ( (lastupdate+timeout) < now);
20     }
21    
22 torben 390 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 torben 1027 public void purgeOldEntries() {
34    
35     long now = android.os.SystemClock.elapsedRealtime();
36 torben 1032 //Log.e("Purge","Purge");
37 torben 1027
38 torben 1032 Set<K> keyset = cache.keySet();
39    
40     for ( Iterator<K> it = keyset.iterator(); it.hasNext() ;) {
41     K key = it.next();
42    
43 torben 1027 CacheItem<V> item = cache.get(key);
44 torben 1033 if ( item.isExpired(now)) { //item too old
45 torben 1032 it.remove();
46     //Log.e("Purge", "removing");
47     }
48     }
49    
50 torben 1027 }
51    
52 torben 390 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 torben 1033 if ( item.isExpired(now) ) { //item too old
65 torben 390 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     }

  ViewVC Help
Powered by ViewVC 1.1.20