package dk.thoerup.traininfo.util; import java.util.HashMap; import java.util.Iterator; import java.util.Set; import android.util.Log; public class AndroidTimeoutCache { class CacheItem { public CacheItem(T v) { value = v; lastupdate = android.os.SystemClock.elapsedRealtime(); } public boolean isExpired(long now) { return ( (lastupdate+timeout) < now); } public long lastupdate; public T value; } private HashMap> cache = new HashMap>(); private long timeout; public AndroidTimeoutCache(int timeout) { this.timeout = timeout; } public void purgeOldEntries() { long now = android.os.SystemClock.elapsedRealtime(); //Log.e("Purge","Purge"); Set keyset = cache.keySet(); for ( Iterator it = keyset.iterator(); it.hasNext() ;) { K key = it.next(); CacheItem item = cache.get(key); if ( item.isExpired(now)) { //item too old it.remove(); //Log.e("Purge", "removing"); } } } public void put(K k, V v) { CacheItem item= new CacheItem(v); cache.put(k, item); } public V get(K k) { long now = android.os.SystemClock.elapsedRealtime(); CacheItem item = cache.get(k); if (item != null) { if ( item.isExpired(now) ) { //item too old return null; } else { return item.value; //item still good } } else { return null; // no item found } } }