-
Notifications
You must be signed in to change notification settings - Fork 33
/
ByteBufferPool.java
413 lines (353 loc) · 14.4 KB
/
ByteBufferPool.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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
/*
* Copyright (c) 2000, 2017 Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2021, 2022 Contributors to the Eclipse Foundation
* Copyright (c) 2020 Payara Services Ltd.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0, which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception, which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
package com.sun.messaging.jmq.io;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;
import java.util.Set;
import java.nio.ByteBuffer;
import com.sun.messaging.jmq.util.DiagManager;
import com.sun.messaging.jmq.util.DiagDictionaryEntry;
/**
*
* A pool of ByteBuffers
*
* Nio direct ByteBuffers are relatively expensive to allocate and deallocate. To make direct ByteBuffers easier to use
* we introduce the ByteBuffer pool. this pool should really be only used for direct ByteBuffers. Standard ByteBuffers
* are better managed by the Java heap.
*
* The pool has the following properties:
*
* poolCapacity: The maximum number of buffer bytes that the pool will hold. poolSize: The number of buffer bytes
* currently in the pool. bigBufSize: The size a buffer needs to be to be considered "big". bigRatio: The max number of
* bytes "big" buffers can occupy in the pool. useDirect: True to allocate direct buffers, false to allocate normal
* blockSize: The allocation block size. This size of all buffers will be a multiple of blockSize.
*
* bigBufSize and bigRatio are used to prevent large buffers from blowing out most of the pool.
*
* The pool is implemented as a HashMap of ArrayLists keyed by buffer size. Each ArrayList holds buffers of one size.
*
*/
public class ByteBufferPool implements DiagManager.Data {
private static boolean DEBUG = false;
// Capacity of buffer pool in bytes
public static final int DEFAULT_CAPACITY = 1024 * 1024;
// Default block size in bytes.
public static final int DEFAULT_BLOCKSIZE = 128;
// Any buffer larger than 64k is considered big
public static final int DEFAULT_BIGBUFSIZE = 64 * 1024;
// By default big buffers can take up half of the pool
public static final float DEFAULT_BIGRATIO = 0.5f;
// Hash table for holding lists of buffers
protected HashMap table = null;
// True if pool is managing direct buffers, else false
protected boolean useDirect = true;
// Allocation block size in bytes. All allocations will be a multiple
// of blockSize. This increases the likelyhood of buffer reuse.
protected int blockSize = DEFAULT_BLOCKSIZE;
// Maximum capacity of the pool in bytes
protected int poolCapacity = DEFAULT_CAPACITY;
// Any buffers this size or larger are considered "big"
protected int bigBufSize = DEFAULT_BIGBUFSIZE;
// Determines the ammount of space in the pool that can be used
// by "big" buffers. This prevents large buffers from taking
// up all the space in the pool
protected float bigRatio = DEFAULT_BIGRATIO;
// Current number of bytes in the pool that are used by big buffers
protected int bigPoolSize = 0;
// Current number of bytes in the pool that are used by all buffers
protected int poolSize = 0;
// Current number of buffers in the pool
protected int nBufs = 0;
// Number of direct bytes allocated. Direct buffers are very expensive
// to allocate and are not free'd efficiently, so once we reach
// our limit of direct bytes to allocate we revert to using
// heap ByteBuffers.
protected int directBytesAllocated = 0;
protected int heapBytesAllocated = 0;
protected int directBufsAllocated = 0;
protected int heapBufsAllocated = 0;
// Diagnostic counters
protected int hits = 0; // # of times we found a buffer in the pool
protected int misses = 0; // # of times we had to allocate a new one
protected int adds = 0; // # of times we added a buffer to the pool
protected int drops = 0; // # of times we failed to add a buffer
// protected int heapDrops = 0;// # of buffers we dropped because they
// were heap buffers
protected String poolContents = null;
protected double utilization = 0;
ArrayList diagDictionary = null;
/**
* Create an empty packet pool with a default capacity that manages direct ByteBuffers. Currently the default capacity
* is 1MB.
*/
public ByteBufferPool() {
this(DEFAULT_CAPACITY, true);
}
/**
* Create an empty packet pool.
*
* @param capacity Capacity in bytes of the pool
* @param useDirect true to manage direct ByteBuffers else false
*/
public ByteBufferPool(int capacity, boolean useDirect) {
this.poolCapacity = capacity;
this.useDirect = useDirect;
table = new HashMap();
DiagManager.register(this);
}
/**
* Set the big buffer size. Any buffer that is this size or larger is considered big.
*/
public void setBigBufSize(int n) {
this.bigBufSize = n;
}
/**
* Get the big buffer size.
*/
public int getBigBufSize() {
return this.bigBufSize;
}
/**
* Set the big ratio for the pool. This ratio determines the number of bytes in the pool that can be occupied by big
* buffers. For example, if the big ratio is 0.5, then half of the pool can be filled with big buffers.
*/
public void setBigRatio(float n) {
this.bigRatio = n;
}
/**
* Get the big ratio.
*/
public float getBigRatio() {
return this.bigRatio;
}
/**
* Set the pool's capacity.
*/
public void setCapacity(int n) {
this.poolCapacity = n;
}
/**
* Get the pool's capacity
*/
public int getCapacity() {
return poolCapacity;
}
/**
* Set the pool's capacity.
*/
public void setBlockSize(int n) {
this.blockSize = n;
}
/**
* Get the pool's capacity
*/
public int getBlockSize() {
return blockSize;
}
/**
* Get utilization as a percentage. Ideal utilization would be 1.0. poor utilization would be 0.1
*/
public double getUtilization() {
return (hits / (double) (hits + misses));
}
/**
* Get a buffer from the pool of at least the specified size. If the pool is empty a newly allocated buffer will be
* returned. ByteBuffer.limit will be set to bufSize. ByteBuffer.capacity may be larger than bufSize.
*/
public synchronized ByteBuffer get(int bufSize) {
ByteBuffer b = null;
// The size of the buffer we allocate is a multiple of the blocksize
int allocateSize = (bufSize / blockSize) * blockSize;
if (bufSize % blockSize > 0) {
allocateSize += blockSize;
}
ArrayList buffers = (ArrayList) table.get(Integer.valueOf(allocateSize));
if (buffers == null || buffers.isEmpty()) {
// No buffer of the correct size in the pool. Allocate one
misses++;
if (directBytesAllocated >= poolCapacity) {
// Once we allocate "poolCapacity" worth of direct bytes
// allocate heap bytes instead.
b = ByteBuffer.allocate(bufSize);
heapBytesAllocated += bufSize;
heapBufsAllocated += 1;
} else if (useDirect) {
b = ByteBuffer.allocateDirect(allocateSize);
directBytesAllocated += allocateSize;
directBufsAllocated += 1;
} else {
b = ByteBuffer.allocate(allocateSize);
}
if (DEBUG) {
System.out.println(super.toString() + " get(): miss: allocating new buffer. Requested " + bufSize + " bytes, allocating " + allocateSize);
}
} else {
b = (ByteBuffer) (buffers.remove(buffers.size() - 1));
poolSize -= b.capacity();
if (b.capacity() >= bigBufSize) {
bigPoolSize -= b.capacity();
}
nBufs--;
hits++;
if (DEBUG) {
System.out.println(super.toString() + " get(): hit: Requested " + bufSize + " bytes, returning " + b.capacity());
}
}
b.limit(bufSize);
b.rewind();
return b;
}
/**
* Return a buffer to the pool. If the pool capacity is exceeded the buffer is not placed in the pool (and presumeably
* left for garbage collection).
*
* Also, if the ByteBuffer.isDirect is inconsitent with the "useDirect" parameter passed in the pool constructor, the
* buffer is disgarded.
*/
public synchronized void put(ByteBuffer b) {
if (b == null) {
return;
}
// If it's a direct pool, only save direct buffers
if (useDirect && !b.isDirect()) {
if (DEBUG) {
System.out.println(super.toString() + " put(): drop: buffer is not direct. " + "Dropping " + b.capacity() + " bytes onto floor ");
}
drops++;
return;
}
ArrayList buffers = null;
boolean bigBuf = false;
// See if it is a big buffer
if (b.capacity() >= bigBufSize) {
bigBuf = true;
}
// If it's a big buffer and we've exceeded the space allowed
// for big buffers, drip it on floor.
if (bigBuf && bigPoolSize > (poolCapacity * bigRatio)) {
drops++;
if (DEBUG) {
System.out.println(super.toString() + " put(): drop: big pool capacity of " + (poolCapacity * bigRatio) + "exceeded. dropping " + b.capacity()
+ " bytes onto floor ");
}
} else if (poolSize < poolCapacity) {
Integer key = Integer.valueOf(b.capacity());
// Add buffer to the pool
buffers = (ArrayList) table.get(key);
if (buffers == null) {
buffers = new ArrayList(64);
table.put(key, buffers);
}
buffers.add(b);
poolSize += b.capacity();
nBufs++;
adds++;
if (bigBuf) {
bigPoolSize += b.capacity();
}
if (DEBUG) {
System.out.println(super.toString() + "put(): add: putting " + b.capacity() + " bytes back into pool");
}
} else {
// Drop it on floor
drops++;
if (DEBUG) {
System.out.println(super.toString() + " put(): drop: dropping " + b.capacity() + " bytes onto floor ");
}
}
}
/**
* Empty the pool.
*/
public synchronized void clear() {
table.clear();
poolSize = 0;
bigPoolSize = 0;
nBufs = 0;
}
@Override
public String toString() {
return super.toString() + ": capacity=" + poolCapacity + ", size=" + poolSize + ", nBufs=" + nBufs + ", bigBufSize=" + bigBufSize + ", bigPoolSize="
+ bigPoolSize + ", bigRatio=" + bigRatio + ", utilization=" + getUtilization() + ", directBytes=" + directBytesAllocated + ", directBuffers="
+ directBufsAllocated + ", heapBytes=" + heapBytesAllocated + ", heapBuffers=" + heapBufsAllocated;
}
public String toDiagString() {
return toString() + ", hits=" + hits + ", misses=" + misses + ", adds=" + adds + ", drops=" + drops;
}
public String poolContents() {
StringBuilder sb = new StringBuilder();
Set set = table.entrySet();
Iterator iter = set.iterator();
int totalBytes = 0;
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
int n = ((Integer) entry.getKey());
ArrayList list = (ArrayList) entry.getValue();
sb.append(n).append(':').append(list.size()).append(' ');
totalBytes += n * list.size();
}
sb.append(" Total Bytes: ").append(totalBytes);
return sb.toString();
}
public void resetDiagCounters() {
hits = 0;
misses = 0;
adds = 0;
drops = 0;
}
// Methods to support diagnostics
@Override
public synchronized List getDictionary() {
if (diagDictionary == null) {
diagDictionary = new ArrayList();
diagDictionary.add(new DiagDictionaryEntry("poolCapacity", DiagManager.VARIABLE));
diagDictionary.add(new DiagDictionaryEntry("poolSize", DiagManager.VARIABLE));
diagDictionary.add(new DiagDictionaryEntry("blockSize", DiagManager.VARIABLE));
diagDictionary.add(new DiagDictionaryEntry("nBufs", DiagManager.VARIABLE));
diagDictionary.add(new DiagDictionaryEntry("bigBufSize", DiagManager.VARIABLE));
diagDictionary.add(new DiagDictionaryEntry("bigPoolSize", DiagManager.VARIABLE));
diagDictionary.add(new DiagDictionaryEntry("directBytesAllocated", DiagManager.COUNTER));
diagDictionary.add(new DiagDictionaryEntry("directBufsAllocated", DiagManager.COUNTER));
diagDictionary.add(new DiagDictionaryEntry("heapBytesAllocated", DiagManager.COUNTER));
diagDictionary.add(new DiagDictionaryEntry("heapBufsAllocated", DiagManager.COUNTER));
diagDictionary.add(new DiagDictionaryEntry("hits", DiagManager.COUNTER));
diagDictionary.add(new DiagDictionaryEntry("misses", DiagManager.COUNTER));
diagDictionary.add(new DiagDictionaryEntry("adds", DiagManager.COUNTER));
diagDictionary.add(new DiagDictionaryEntry("drops", DiagManager.COUNTER));
diagDictionary.add(new DiagDictionaryEntry("utilization", DiagManager.VARIABLE));
diagDictionary.add(new DiagDictionaryEntry("poolContents", DiagManager.VARIABLE));
}
return diagDictionary;
}
@Override
public void update() {
poolContents = "[" + poolContents() + "]";
utilization = getUtilization();
}
@Override
public String getPrefix() {
return "bbpool";
}
@Override
public String getTitle() {
return "ByteBufferPool";
}
}