/[projects]/android/TrainInfoService/src/dk/thoerup/traininfoservice/banedk/TimeoutCache.java
ViewVC logotype

Contents of /android/TrainInfoService/src/dk/thoerup/traininfoservice/banedk/TimeoutCache.java

Parent Directory Parent Directory | Revision Log Revision Log


Revision 387 - (show annotations) (download)
Fri Oct 2 15:06:08 2009 UTC (14 years, 7 months ago) by torben
File size: 898 byte(s)
Enable caching for departures and timetables
1 package dk.thoerup.traininfoservice.banedk;
2
3 import java.util.concurrent.ConcurrentHashMap;
4
5
6 public class TimeoutCache<K,V> {
7
8 class CacheItem<T> {
9
10 public CacheItem(T v) {
11 value = v;
12 lastupdate = System.currentTimeMillis();
13 }
14
15 public long lastupdate;
16 public T value;
17 }
18
19 private ConcurrentHashMap<K,CacheItem<V>> cache = new ConcurrentHashMap<K,CacheItem<V>>();
20 private long timeout;
21
22 public TimeoutCache(int timeout) {
23 this.timeout = timeout;
24 }
25
26 public void put(K k, V v) {
27 CacheItem<V> item= new CacheItem<V>(v);
28 cache.put(k, item);
29 }
30
31 public V get(K k) {
32 long now = System.currentTimeMillis();
33
34 CacheItem<V> item = cache.get(k);
35
36
37 if (item != null) {
38 if ( (item.lastupdate+timeout) < now) { //item too old
39 return null;
40 } else {
41 return item.value; //item still good
42 }
43 } else {
44 return null; // no item found
45 }
46
47 }
48
49 }

  ViewVC Help
Powered by ViewVC 1.1.20