-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
DefaultTimeoutMap.java
287 lines (250 loc) · 9.51 KB
/
DefaultTimeoutMap.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.support;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.camel.TimeoutMap;
import org.apache.camel.support.service.ServiceSupport;
import org.apache.camel.util.ObjectHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static java.util.Comparator.comparing;
import static org.apache.camel.TimeoutMap.Listener.Type.Evict;
import static org.apache.camel.TimeoutMap.Listener.Type.Put;
import static org.apache.camel.TimeoutMap.Listener.Type.Remove;
/**
* Default implementation of the {@link TimeoutMap}.
* <p/>
* This implementation supports thread safe and non thread safe, in the manner you can enable locking or not. By default
* locking is enabled and thus we are thread safe.
* <p/>
* You must provide a {@link java.util.concurrent.ScheduledExecutorService} in the constructor which is used to schedule
* a background task which check for old entries to purge. This implementation will shutdown the scheduler if its being
* stopped. You must also invoke {@link #start()} to startup the timeout map, before its ready to be used. And you must
* invoke {@link #stop()} to stop the map when no longer in use.
*/
public class DefaultTimeoutMap<K, V> extends ServiceSupport implements TimeoutMap<K, V> {
protected final Logger log = LoggerFactory.getLogger(getClass());
private final ConcurrentMap<K, TimeoutMapEntry<K, V>> map = new ConcurrentHashMap<>();
private final ScheduledExecutorService executor;
private volatile ScheduledFuture<?> future;
private final long purgePollTime;
private final Lock lock;
private final List<Listener<K, V>> listeners = new ArrayList<>(2);
public DefaultTimeoutMap(ScheduledExecutorService executor) {
this(executor, 1000);
}
public DefaultTimeoutMap(ScheduledExecutorService executor, long requestMapPollTimeMillis) {
this(executor, requestMapPollTimeMillis, true);
}
public DefaultTimeoutMap(ScheduledExecutorService executor, long requestMapPollTimeMillis, boolean useLock) {
this(executor, requestMapPollTimeMillis, useLock ? new ReentrantLock() : NoLock.INSTANCE);
}
public DefaultTimeoutMap(ScheduledExecutorService executor, long requestMapPollTimeMillis, Lock lock) {
ObjectHelper.notNull(executor, "ScheduledExecutorService");
this.executor = executor;
this.purgePollTime = requestMapPollTimeMillis;
this.lock = lock;
}
@Override
public V get(K key) {
TimeoutMapEntry<K, V> entry;
// if no contains, the lock is not necessary
if (!map.containsKey(key)) {
return null;
}
lock.lock();
try {
entry = map.get(key);
if (entry == null) {
return null;
}
updateExpireTime(entry);
} finally {
lock.unlock();
}
return entry.getValue();
}
@Override
public V put(K key, V value, long timeoutMillis) {
TimeoutMapEntry<K, V> entry = new TimeoutMapEntry<>(key, value, timeoutMillis);
lock.lock();
try {
updateExpireTime(entry);
TimeoutMapEntry<K, V> result = map.put(key, entry);
return unwrap(result);
} finally {
lock.unlock();
emitEvent(Put, key, value);
}
}
@Override
public V putIfAbsent(K key, V value, long timeoutMillis) {
TimeoutMapEntry<K, V> entry = new TimeoutMapEntry<>(key, value, timeoutMillis);
TimeoutMapEntry<K, V> result = null;
lock.lock();
try {
updateExpireTime(entry);
//Just make sure we don't override the old entry
result = map.putIfAbsent(key, entry);
return unwrap(result);
} finally {
lock.unlock();
if (result != entry) {
emitEvent(Put, key, value); // conditional on map being changed
}
}
}
@Override
public V remove(K key) {
V value = null;
lock.lock();
try {
value = unwrap(map.remove(key));
return value;
} finally {
lock.unlock();
if (value != null) {
emitEvent(Remove, key, value); // conditional on map being changed
}
}
}
@Override
public int size() {
return map.size();
}
/**
* The timer task which purges old requests and schedules another poll
*/
private void purgeTask() {
// only purge if allowed
if (!isRunAllowed()) {
log.trace("Purge task not allowed to run");
return;
}
log.trace("Running purge task to see if any entries have been timed out");
try {
purge();
} catch (Throwable t) {
// must catch and log exception otherwise the executor will now schedule next purgeTask
log.warn("Exception occurred during purge task. This exception will be ignored.", t);
}
}
protected void purge() {
log.trace("There are {} in the timeout map", map.size());
if (map.isEmpty()) {
return;
}
long now = currentTime();
List<TimeoutMapEntry<K, V>> expired = new ArrayList<>(map.size());
lock.lock();
try {
// need to find the expired entries and add to the expired list
for (Map.Entry<K, TimeoutMapEntry<K, V>> entry : map.entrySet()) {
if (entry.getValue().getExpireTime() < now) {
if (isValidForEviction(entry.getValue())) {
log.debug("Evicting inactive entry ID: {}", entry.getValue());
expired.add(entry.getValue());
}
}
}
// if we found any expired then we need to sort, onEviction and remove
if (!expired.isEmpty()) {
// sort according to the expired time so we got the first expired first
expired.sort(comparing(TimeoutMapEntry::getExpireTime));
// and must remove from list after we have fired the notifications
for (TimeoutMapEntry<K, V> entry : expired) {
map.remove(entry.getKey());
}
}
} finally {
lock.unlock();
for (TimeoutMapEntry<K, V> entry : expired) {
emitEvent(Evict, entry.getKey(), entry.getValue());
}
}
}
// Properties
// -------------------------------------------------------------------------
public long getPurgePollTime() {
return purgePollTime;
}
public ScheduledExecutorService getExecutor() {
return executor;
}
// Implementation methods
// -------------------------------------------------------------------------
private static <K, V> V unwrap(TimeoutMapEntry<K, V> entry) {
return entry == null ? null : entry.getValue();
}
@Override
public void addListener(Listener<K, V> listener) {
this.listeners.add(listener);
}
private void emitEvent(Listener.Type type, K key, V value) {
for (Listener<K, V> listener : listeners) {
try {
listener.timeoutMapEvent(type, key, value);
} catch (Throwable t) {
// Ignore
}
}
}
/**
* lets schedule each time to allow folks to change the time at runtime
*/
protected void schedulePoll() {
future = executor.scheduleWithFixedDelay(this::purgeTask, 0, purgePollTime, TimeUnit.MILLISECONDS);
}
/**
* A hook to allow derivations to avoid evicting the current entry
*/
protected boolean isValidForEviction(TimeoutMapEntry<K, V> entry) {
return true;
}
protected void updateExpireTime(TimeoutMapEntry<K, V> entry) {
long now = currentTime();
entry.setExpireTime(entry.getTimeout() + now);
}
protected long currentTime() {
return System.currentTimeMillis();
}
@Override
protected void doStart() throws Exception {
if (executor.isShutdown()) {
throw new IllegalStateException("The ScheduledExecutorService is shutdown");
}
schedulePoll();
}
@Override
protected void doStop() throws Exception {
if (future != null) {
future.cancel(false);
future = null;
}
// clear map if we stop
map.clear();
}
}