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 arg0) { |
40 |
CacheItem<V> item = cache.get(arg0); |
41 |
|
42 |
return (item != null); |
43 |
} |
44 |
|
45 |
@Override |
46 |
public boolean containsValue(Object arg0) { |
47 |
return values().contains(arg0); |
48 |
} |
49 |
|
50 |
@Override |
51 |
public Set<java.util.Map.Entry<K, V>> entrySet() { |
52 |
//TODO someday implement this |
53 |
throw new UnsupportedOperationException(); |
54 |
} |
55 |
|
56 |
@Override |
57 |
public boolean isEmpty() { |
58 |
return cache.isEmpty(); |
59 |
} |
60 |
|
61 |
@Override |
62 |
public Set<K> keySet() { |
63 |
return cache.keySet(); |
64 |
} |
65 |
|
66 |
@Override |
67 |
public void putAll(Map<? extends K, ? extends V> arg0) { |
68 |
for(K key : arg0.keySet()) { |
69 |
this.put(key, arg0.get(key) ); |
70 |
} |
71 |
} |
72 |
|
73 |
@Override |
74 |
public V remove(Object arg0) { |
75 |
return cache.remove(arg0).value; |
76 |
} |
77 |
|
78 |
@Override |
79 |
public int size() { |
80 |
return cache.size(); |
81 |
} |
82 |
|
83 |
@Override |
84 |
public Collection<V> values() { |
85 |
ArrayList<V> values = new ArrayList<V>(); |
86 |
for (CacheItem<V> item : cache.values()) { |
87 |
values.add( item.value ); |
88 |
} |
89 |
|
90 |
return values; |
91 |
|
92 |
} |
93 |
|
94 |
@Override |
95 |
public V get(Object key) { |
96 |
long now = System.currentTimeMillis(); |
97 |
|
98 |
CacheItem<V> item = cache.get(key); |
99 |
|
100 |
|
101 |
if (item != null) { |
102 |
if ( (item.lastupdate+timeout) < now) { //item too old |
103 |
return null; |
104 |
} else { |
105 |
return item.value; //item still good |
106 |
} |
107 |
} else { |
108 |
return null; // no item found |
109 |
} |
110 |
} |
111 |
|
112 |
@Override |
113 |
public V put(K key, V value) { |
114 |
CacheItem<V> item= new CacheItem<V>(value); |
115 |
|
116 |
item = cache.put(key, item); |
117 |
|
118 |
if (item != null) |
119 |
return item.value; |
120 |
else |
121 |
return null; |
122 |
} |
123 |
|
124 |
} |