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

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

Parent Directory Parent Directory | Revision Log Revision Log


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

Properties

Name Value
svn:mergeinfo

  ViewVC Help
Powered by ViewVC 1.1.20