ByteBufferChunk.java
8.16 KB
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
package io.mycat.buffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.nio.ch.DirectBuffer;
import java.nio.ByteBuffer;
/**
* 仿照Netty的思路,针对MyCat内存缓冲策略优化
* Chunk由Page组成,是一块连续内存,由memoryMap和depthMap定义成一种平衡二叉树的管理结构
*
* @author Hash Zhang
* @version 1.0
* @time 17:19 2016/5/17
* @see @https://github.com/netty/netty
*/
public class ByteBufferChunk implements Comparable{
private static final Logger LOGGER = LoggerFactory.getLogger(ByteBufferChunk.class);
private final byte[] memoryMap;
private final byte[] depthMap;
private final ByteBuffer buf;
//in bytes
private final int pageSize;
//in bytes
private final int chunkSize;
private final int chunkPageSize;
private final int maxOrder;
private final byte unusable;
private final int log2PageSize;
final long bufAddress;
private int freeBytes;
ByteBufferChunk prev;
ByteBufferChunk next;
ByteBufferChunkList parent;
public ByteBufferChunk(int pageSize, int chunkSize) {
this.pageSize = pageSize;
this.chunkSize = chunkSize;
this.chunkPageSize = chunkSize / pageSize;
this.maxOrder = log2(this.chunkPageSize) + 1;
this.unusable = (byte) this.maxOrder;
this.freeBytes = chunkSize;
this.buf = ByteBuffer.allocateDirect(chunkSize);
this.bufAddress = ((DirectBuffer) buf).address();
this.depthMap = new byte[(1 << this.maxOrder)];
this.memoryMap = new byte[this.depthMap.length];
this.log2PageSize = log2(pageSize);
int memoryMapIndex = 1;
for (int d = 0; d < maxOrder; ++d) { // move down the tree one level at a time
int depth = 1 << d;
for (int p = 0; p < depth; ++p) {
// in each level traverse left to right and set value to the depth of subtree
memoryMap[memoryMapIndex] = (byte) d;
depthMap[memoryMapIndex] = (byte) d;
memoryMapIndex++;
}
}
}
public boolean isInThisChunk(ByteBuffer byteBuffer) {
long address = ((DirectBuffer) byteBuffer).address();
return (address >= bufAddress) && (address < bufAddress + chunkSize);
}
public int usage() {
final int freeBytes = this.freeBytes;
if (freeBytes == 0) {
return 100;
}
int freePercentage = (int) (freeBytes * 100L / chunkSize);
if (freePercentage == 0) {
return 99;
}
return 100 - freePercentage;
}
public synchronized ByteBuffer allocateRun(int normCapacity) {
if(normCapacity > chunkSize){
LOGGER.warn("try to acquire a buffer with larger size than chunkSize!");
return null;
}
int d = this.maxOrder - 2 - (log2(normCapacity) - this.log2PageSize);
if (d > this.maxOrder - 1) {
d = maxOrder - 1;
}
int id = allocateNode(d);
if (id < 0) {
return null;
}
freeBytes -= runLength(id);
int start = calculateStart(id);
int end = start + runLength(id);
buf.limit(end);
buf.position(start);
// printMemoryMap();
return buf.slice();
}
private int calculateStart(int id) {
int count = 0;
for (int i = 1; i < depthMap.length; i++) {
if (depthMap[i] < depthMap[id]) {
continue;
} else if (depthMap[i] == depthMap[id]) {
if (i == id) {
break;
} else {
count += runLength(i);
}
} else {
break;
}
}
return count;
}
private int runLength(int id) {
// represents the size in #bytes supported by node 'id' in the tree
return 1 << log2(chunkSize) - depthMap[id];
}
private int allocateNode(int d) {
int id = 1;
int initial = -(1 << d); // has last d bits = 0 and rest all = 1
byte val = memoryMap[id];
if (val > d) { // unusable
return -1;
}
while (val < d || (id & initial) == 0) { // id & initial == 1 << d for all ids at depth d, for < d it is 0
id <<= 1;
val = memoryMap[id];
if (val > d) {
id ^= 1;
val = memoryMap[id];
}
}
byte value = memoryMap[id];
assert value == d && (id & initial) == 1 << d : String.format("val = %d, id & initial = %d, d = %d",
value, id & initial, d);
memoryMap[id] = unusable; // mark as unusable
updateParentsAlloc(id);
return id;
}
private void updateParentsAlloc(int id) {
while (id > 1) {
int parentId = id >>> 1;
byte val1 = memoryMap[id];
byte val2 = memoryMap[id ^ 1];
byte val = val1 < val2 ? val1 : val2;
memoryMap[parentId] = val;
id = parentId;
}
}
public synchronized void freeByteBuffer(ByteBuffer byteBuffer) {
long address = ((DirectBuffer) byteBuffer).address();
int relativeAddress = (int) (address - bufAddress);
int length = byteBuffer.capacity();
int depth = maxOrder - 1 - log2(length / pageSize);
int count = 0;
int i;
for (i = 0; i < depthMap.length; i++) {
if (depthMap[i] == depth) {
if (count == relativeAddress) {
break;
}
count += length;
}
if (depthMap[i] > depth) {
break;
}
}
free(i);
}
private void free(int handle) {
if (memoryMap[handle] != depthMap[handle]) {
freeBytes += runLength(handle);
memoryMap[handle] = depthMap[handle];
updateParentsFree(handle);
}
}
private void updateParentsFree(int id) {
int logChild = depthMap[id] + 1;
while (id > 1) {
int parentId = id >>> 1;
byte val1 = memoryMap[id];
byte val2 = memoryMap[id ^ 1];
logChild -= 1; // in first iteration equals log, subsequently reduce 1 from logChild as we traverse up
if (val1 == logChild && val2 == logChild) {
memoryMap[parentId] = (byte) (logChild - 1);
} else {
byte val = val1 < val2 ? val1 : val2;
memoryMap[parentId] = val;
}
id = parentId;
}
}
private static int log2(int chunkSize) {
if (chunkSize <= 0) {
LOGGER.warn("invalid parameter!");
throw new IllegalArgumentException();
}
return Integer.SIZE - 1 - Integer.numberOfLeadingZeros(chunkSize);
}
private void printMemoryMap() {
int l = 1;
for (int i = 0; i < this.maxOrder; i++) {
int j = (int) Math.pow(2, i);
for (int k = 0; k < j; k++) {
System.out.print(this.memoryMap[l] + "|");
l++;
}
System.out.println();
}
System.out.println();
}
public static void main(String[] args) {
int pageSize = 256;
int chunkSize = 1024 * 1024 * 64;
ByteBufferChunk byteBufferChunk = new ByteBufferChunk(pageSize, chunkSize);
int chunkCount = 8;
int allocTimes = 102400;
long start = System.currentTimeMillis();
for (int i = 0; i < allocTimes; i++) {
// System.out.println("allocate "+i);
// long start=System.nanoTime();
int size = 256;
ByteBuffer byteBufer = byteBufferChunk.allocateRun(size);
// System.out.println("alloc "+size+" usage "+(System.nanoTime()-start));
// start=System.nanoTime();
// byteBufferArena.recycle(byteBufer);
// System.out.println("recycle usage "+(System.nanoTime()-start));
}
long used = (System.currentTimeMillis() - start);
System.out.println("total used time " + used + " avg speed " + allocTimes / used);
}
@Override
public int compareTo(Object o) {
return -1;
}
}