1 |
package dk.thoerup.traininfoservice.banedk; |
2 |
|
3 |
import java.util.ArrayList; |
4 |
import java.util.Collection; |
5 |
import java.util.Map; |
6 |
import java.util.Set; |
7 |
import java.util.concurrent.ConcurrentHashMap; |
8 |
|
9 |
|
10 |
|
11 |
public class TimeoutMap<K,V> implements Map<K,V>{ |
12 |
|
13 |
class CacheItem<T> { |
14 |
|
15 |
public CacheItem(T v) { |
16 |
value = v; |
17 |
lastupdate = System.currentTimeMillis(); |
18 |
} |
19 |
|
20 |
public long lastupdate; |
21 |
public T value; |
22 |
} |
23 |
|
24 |
private ConcurrentHashMap<K,CacheItem<V>> cache = new ConcurrentHashMap<K,CacheItem<V>>(); |
25 |
private long timeout; |
26 |
|
27 |
public TimeoutMap(int timeout) { |
28 |
this.timeout = timeout; |
29 |
} |
30 |
|
31 |
|
32 |
@Override |
33 |
public void clear() { |
34 |
cache.clear(); |
35 |
|
36 |
} |
37 |
|
38 |
@Override |
39 |
public boolean containsKey(Object key) { |
40 |
return cache.containsKey(key); |
41 |
} |
42 |
|
43 |
@Override |
44 |
public boolean containsValue(Object arg0) { |
45 |
//return values().contains(arg0); |
46 |
throw new UnsupportedOperationException(); |
47 |
} |
48 |
|
49 |
@Override |
50 |
public Set<java.util.Map.Entry<K, V>> entrySet() { |
51 |
//TODO someday implement this |
52 |
throw new UnsupportedOperationException(); |
53 |
} |
54 |
|
55 |
@Override |
56 |
public boolean isEmpty() { |
57 |
return cache.isEmpty(); |
58 |
} |
59 |
|
60 |
@Override |
61 |
public Set<K> keySet() { |
62 |
return cache.keySet(); |
63 |
} |
64 |
|
65 |
@Override |
66 |
public void putAll(Map<? extends K, ? extends V> arg0) { |
67 |
for(K key : arg0.keySet()) { |
68 |
this.put(key, arg0.get(key) ); |
69 |
} |
70 |
} |
71 |
|
72 |
@Override |
73 |
public V remove(Object arg0) { |
74 |
return cache.remove(arg0).value; |
75 |
} |
76 |
|
77 |
@Override |
78 |
public int size() { |
79 |
return cache.size(); |
80 |
} |
81 |
|
82 |
@Override |
83 |
public Collection<V> values() { |
84 |
ArrayList<V> values = new ArrayList<V>(); |
85 |
for (CacheItem<V> item : cache.values()) { |
86 |
values.add( item.value ); |
87 |
} |
88 |
|
89 |
return values; |
90 |
|
91 |
} |
92 |
|
93 |
@Override |
94 |
public V get(Object key) { |
95 |
long now = System.currentTimeMillis(); |
96 |
|
97 |
CacheItem<V> item = cache.get(key); |
98 |
|
99 |
|
100 |
if (item != null) { |
101 |
if ( (item.lastupdate+timeout) < now) { //item too old |
102 |
return null; |
103 |
} else { |
104 |
return item.value; //item still good |
105 |
} |
106 |
} else { |
107 |
return null; // no item found |
108 |
} |
109 |
} |
110 |
|
111 |
@Override |
112 |
public V put(K key, V value) { |
113 |
CacheItem<V> item= new CacheItem<V>(value); |
114 |
|
115 |
item = cache.put(key, item); |
116 |
|
117 |
if (item != null) |
118 |
return item.value; |
119 |
else |
120 |
return null; |
121 |
} |
122 |
|
123 |
} |