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