forked from voldemort/voldemort
/
QueuedKeyedResourcePool.java
337 lines (299 loc) · 11.9 KB
/
QueuedKeyedResourcePool.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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
package voldemort.utils.pool;
import java.util.Map.Entry;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentMap;
import org.apache.log4j.Logger;
import voldemort.store.UnreachableStoreException;
/**
* Extends simple implementation of a per-key resource pool with a non-blocking
* interface to enqueue requests for a resource when one becomes available. <br>
* <ul>
* <li>allocates resources in FIFO order
* <li>Pools are per key and there is no global maximum pool limit.
* </ul>
*/
public class QueuedKeyedResourcePool<K, V> extends KeyedResourcePool<K, V> {
public interface ResourceRequest<V> {
// Invoked with checked out resource; resource guaranteed to be
// not-null.
void useResource(V resource);
// Invoked sometime after deadline. Will never invoke useResource.
void handleTimeout();
// Invoked upon resource pool exception. Will never invoke useResource.
void handleException(Exception e);
// Returns deadline (in nanoseconds), after which handleTimeout()
// should be invoked.
long getDeadlineNs();
}
private static final Logger logger = Logger.getLogger(QueuedKeyedResourcePool.class.getName());
private final ConcurrentMap<K, Queue<ResourceRequest<V>>> requestQueueMap;
public QueuedKeyedResourcePool(ResourceFactory<K, V> objectFactory, ResourcePoolConfig config) {
super(objectFactory, config);
requestQueueMap = new ConcurrentHashMap<K, Queue<ResourceRequest<V>>>();
}
/**
* Create a new queued pool
*
* @param <K> The type of the keys
* @param <R> The type of requests
* @param <V> The type of the values
* @param factory The factory that creates objects
* @param config The pool config
* @return The created pool
*/
public static <K, V> QueuedKeyedResourcePool<K, V> create(ResourceFactory<K, V> factory,
ResourcePoolConfig config) {
return new QueuedKeyedResourcePool<K, V>(factory, config);
}
/**
* Create a new queued pool using the defaults
*
* @param <K> The type of the keys
* @param <R> The type of requests
* @param <V> The type of the values
* @param factory The factory that creates objects
* @return The created pool
*/
public static <K, V> QueuedKeyedResourcePool<K, V> create(ResourceFactory<K, V> factory) {
return create(factory, new ResourcePoolConfig());
}
/**
* This method is the asynchronous (nonblocking) version of
* KeyedResourcePool.checkout. This method necessarily has a different
* function declaration (i.e., arguments passed and return type).
*
* This method either checks out a resource and uses that resource or
* enqueues a request to checkout the resource. I.e., there is a
* non-blocking fast-path that is tried optimistically.
*
* @param key The key to checkout the resource for
* @return The resource
*
*/
public void requestResource(K key, ResourceRequest<V> resourceRequest) {
checkNotClosed();
// Non-blocking checkout attempt iff requestQueue is empty. If
// requestQueue is not empty and we attempted non-blocking checkout,
// then FIFO at risk.
Queue<ResourceRequest<V>> requestQueue = getRequestQueueForKey(key);
if(requestQueue.isEmpty()) {
Pool<V> resourcePool = getResourcePoolForKey(key);
try {
attemptGrow(key, resourcePool);
} catch(Exception e) {
resourceRequest.handleException(e);
return;
}
V resource = null;
try {
resource = attemptCheckout(resourcePool);
} catch(Exception e) {
super.destroyResource(key, resourcePool, resource);
resourceRequest.handleException(e);
}
if(resource != null) {
// TODO: Is another try/catch block needed anywhere to ensure
// resource is destroyed if/when anything bad happens in
// useResource method?
resourceRequest.useResource(resource);
return;
}
}
requestQueue.add(resourceRequest);
}
/**
* Pops resource requests off the queue until queue is empty or an unexpired
* resource request is found. Invokes .handleTimeout on all expired resource
* requests popped off the queue.
*
* @return null or a valid ResourceRequest
*/
private ResourceRequest<V> getNextUnexpiredResourceRequest(Queue<ResourceRequest<V>> requestQueue) {
ResourceRequest<V> resourceRequest = requestQueue.poll();
while(resourceRequest != null) {
if(resourceRequest.getDeadlineNs() < System.nanoTime()) {
resourceRequest.handleTimeout();
resourceRequest = requestQueue.poll();
} else {
break;
}
}
return resourceRequest;
}
/**
* Attempts to checkout a resource so that one queued request can be
* serviced.
*
* @param key The key for which to process the requestQueue
* @return true iff an item was processed from the Queue.
*/
private boolean processQueue(K key) throws Exception {
Queue<ResourceRequest<V>> requestQueue = getRequestQueueForKey(key);
if(requestQueue.isEmpty()) {
return false;
}
// Attempt to get a resource.
Pool<V> resourcePool = getResourcePoolForKey(key);
V resource = null;
try {
// Always attempt to grow to deal with destroyed resources.
attemptGrow(key, resourcePool);
resource = attemptCheckout(resourcePool);
} catch(Exception e) {
super.destroyResource(key, resourcePool, resource);
}
if(resource == null) {
return false;
}
// With resource in hand, process the resource requests
ResourceRequest<V> resourceRequest = getNextUnexpiredResourceRequest(requestQueue);
if(resourceRequest == null) {
// Did not use the resource!
super.checkin(key, resource);
return false;
}
resourceRequest.useResource(resource);
return true;
}
/**
* Check the given resource back into the pool
*
* @param key The key for the resource
* @param resource The resource
*/
@Override
public void checkin(K key, V resource) throws Exception {
// TODO: Unclear if invoking checkin and then invoking processQueue is
// "fair" or is "FIFO". In particular, is super.checkout invoked
// directly? If so, how should such a blocking checkout interact with
// non-blocking checkouts?
super.checkin(key, resource);
while(processQueue(key)) {}
}
/*
* A safe wrapper to destroy the given resource request.
*/
protected void destroyRequest(ResourceRequest<V> resourceRequest) {
if(resourceRequest != null) {
try {
Exception e = new UnreachableStoreException("Resource request destroyed before resource checked out.");
resourceRequest.handleException(e);
} catch(Exception ex) {
logger.error("Exception while destroying resource request:", ex);
}
}
}
/**
* Destroys all resource requests in requestQueue.
*
* @param requestQueue The queue for which all resource requests are to be
* destroyed.
*/
private void destroyRequestQueue(Queue<ResourceRequest<V>> requestQueue) {
ResourceRequest<V> resourceRequest = requestQueue.poll();
while(resourceRequest != null) {
destroyRequest(resourceRequest);
resourceRequest = requestQueue.poll();
}
}
@Override
protected boolean internalClose() {
// wasOpen ensures only one thread destroys everything.
boolean wasOpen = super.internalClose();
if(wasOpen) {
for(Entry<K, Queue<ResourceRequest<V>>> entry: requestQueueMap.entrySet()) {
Queue<ResourceRequest<V>> requestQueue = entry.getValue();
destroyRequestQueue(requestQueue);
requestQueueMap.remove(entry.getKey());
}
}
return wasOpen;
}
/**
* Close the queue and the pool.
*/
@Override
public void close() {
internalClose();
}
/**
* "Close" a specific resource pool and request queue by destroying all the
* resources in the pool and all the requests in the queue. This method does
* not affect whether any pool or queue is "open" in the sense of permitting
* new resources to be added or requests to be enqueued.
*
* @param key The key for the pool to close.
*/
@Override
public void close(K key) {
// TODO: The close method in the super class is not documented at all.
// super.close(key) is called by ClientRequestExecutorPool.close which
// is called by SocketStoreclientFactory. Given the super class does not
// set any closed bit, unclear what the semantics of this.close(key)
// ought to be.
//
// Also, super.close(key) does nothing to protect against multiple
// threads accessing the method at the same time. And, super.close(key)
// does not remove the affected pool from super.resourcePoolMap. The
// semantics of super.close(key) are truly unclear.
// Destroy enqueued resource requests (if any exist) first.
Queue<ResourceRequest<V>> requestQueue = requestQueueMap.get(key);
if(requestQueue != null) {
destroyRequestQueue(requestQueue);
// TODO: requestQueueMap.remove(entry.getKey()); ?
}
// Destroy resources in the pool second.
super.close(key);
}
/*
* Get the queue of work for the given key. If no queue exists, create one.
*/
protected Queue<ResourceRequest<V>> getRequestQueueForKey(K key) {
Queue<ResourceRequest<V>> requestQueue = requestQueueMap.get(key);
if(requestQueue == null) {
requestQueue = new ConcurrentLinkedQueue<ResourceRequest<V>>();
requestQueueMap.putIfAbsent(key, requestQueue);
requestQueue = requestQueueMap.get(key);
}
return requestQueue;
}
/*
* Get the pool for the given key. If no pool exists, throw an exception.
*/
protected Queue<ResourceRequest<V>> getRequestQueueForExistingKey(K key) {
Queue<ResourceRequest<V>> requestQueue = requestQueueMap.get(key);
if(requestQueue == null) {
throw new IllegalArgumentException("Invalid key '" + key
+ "': no request queue exists for that key.");
}
return requestQueue;
}
/**
* Return the number of requests queued up for a given pool.
*
* @param key The key
* @return The count
*/
public int getQueuedResourceRequestCount(K key) {
Queue<ResourceRequest<V>> requestQueue = getRequestQueueForExistingKey(key);
// FYI: .size() is not constant time in the next call. ;)
return requestQueue.size();
}
/**
* Return the number of resource requests queued up for all pools.
*
* @return The count of resources
*/
public int getQueuedResourceRequestCount() {
int count = 0;
for(Entry<K, Queue<ResourceRequest<V>>> entry: this.requestQueueMap.entrySet()) {
// FYI: .size() is not constant time in the next call. ;)
count += entry.getValue().size();
}
// count is approximate in the case of concurrency since .queue.size()
// for various entries can change while other entries are being counted.
return count;
}
}