1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.buffer;
17
18 import io.netty.util.ByteProcessor;
19 import io.netty.util.IllegalReferenceCountException;
20 import io.netty.util.NettyRuntime;
21 import io.netty.util.Recycler.EnhancedHandle;
22 import io.netty.util.ReferenceCounted;
23 import io.netty.util.concurrent.FastThreadLocal;
24 import io.netty.util.concurrent.FastThreadLocalThread;
25 import io.netty.util.internal.ObjectPool;
26 import io.netty.util.internal.ObjectUtil;
27 import io.netty.util.internal.PlatformDependent;
28 import io.netty.util.internal.ReferenceCountUpdater;
29 import io.netty.util.internal.SystemPropertyUtil;
30 import io.netty.util.internal.ThreadExecutorMap;
31 import io.netty.util.internal.UnstableApi;
32
33 import java.io.IOException;
34 import java.io.InputStream;
35 import java.io.OutputStream;
36 import java.nio.ByteBuffer;
37 import java.nio.ByteOrder;
38 import java.nio.channels.ClosedChannelException;
39 import java.nio.channels.FileChannel;
40 import java.nio.channels.GatheringByteChannel;
41 import java.nio.channels.ScatteringByteChannel;
42 import java.util.Arrays;
43 import java.util.Queue;
44 import java.util.Set;
45 import java.util.concurrent.ConcurrentLinkedQueue;
46 import java.util.concurrent.CopyOnWriteArraySet;
47 import java.util.concurrent.ThreadLocalRandom;
48 import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
49 import java.util.concurrent.atomic.AtomicLong;
50 import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
51 import java.util.concurrent.locks.StampedLock;
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 @UnstableApi
80 final class AdaptivePoolingAllocator {
81
82 enum MagazineCaching {
83 EventLoopThreads,
84 FastThreadLocalThreads,
85 None
86 }
87
88
89
90
91
92
93
94
95 private static final int MIN_CHUNK_SIZE = 128 * 1024;
96 private static final int EXPANSION_ATTEMPTS = 3;
97 private static final int INITIAL_MAGAZINES = 4;
98 private static final int RETIRE_CAPACITY = 4 * 1024;
99 private static final int MAX_STRIPES = NettyRuntime.availableProcessors() * 2;
100 private static final int BUFS_PER_CHUNK = 10;
101
102
103
104
105
106
107 private static final int MAX_CHUNK_SIZE =
108 BUFS_PER_CHUNK * (1 << AllocationStatistics.HISTO_MAX_BUCKET_SHIFT);
109
110
111
112
113
114
115
116
117
118 private static final int CENTRAL_QUEUE_CAPACITY = Math.max(2, SystemPropertyUtil.getInt(
119 "io.netty.allocator.centralQueueCapacity", NettyRuntime.availableProcessors()));
120
121
122
123
124
125 private static final int MAGAZINE_BUFFER_QUEUE_CAPACITY = SystemPropertyUtil.getInt(
126 "io.netty.allocator.magazineBufferQueueCapacity", 1024);
127
128 private static final Object NO_MAGAZINE = Boolean.TRUE;
129
130 private final ChunkAllocator chunkAllocator;
131 private final Queue<Chunk> centralQueue;
132 private final StampedLock magazineExpandLock;
133 private volatile Magazine[] magazines;
134 private final FastThreadLocal<Object> threadLocalMagazine;
135 private final Set<Magazine> liveCachedMagazines;
136 private volatile boolean freed;
137
138 static {
139 if (MAGAZINE_BUFFER_QUEUE_CAPACITY < 2) {
140 throw new IllegalArgumentException("MAGAZINE_BUFFER_QUEUE_CAPACITY: " + MAGAZINE_BUFFER_QUEUE_CAPACITY
141 + " (expected: >= " + 2 + ')');
142 }
143 }
144
145 AdaptivePoolingAllocator(ChunkAllocator chunkAllocator, MagazineCaching magazineCaching) {
146 ObjectUtil.checkNotNull(chunkAllocator, "chunkAllocator");
147 ObjectUtil.checkNotNull(magazineCaching, "magazineCaching");
148 this.chunkAllocator = chunkAllocator;
149 centralQueue = ObjectUtil.checkNotNull(createSharedChunkQueue(), "centralQueue");
150 magazineExpandLock = new StampedLock();
151 if (magazineCaching != MagazineCaching.None) {
152 assert magazineCaching == MagazineCaching.EventLoopThreads ||
153 magazineCaching == MagazineCaching.FastThreadLocalThreads;
154 final boolean cachedMagazinesNonEventLoopThreads =
155 magazineCaching == MagazineCaching.FastThreadLocalThreads;
156 final Set<Magazine> liveMagazines = new CopyOnWriteArraySet<Magazine>();
157 threadLocalMagazine = new FastThreadLocal<Object>() {
158 @Override
159 protected Object initialValue() {
160 if (cachedMagazinesNonEventLoopThreads || ThreadExecutorMap.currentExecutor() != null) {
161 if (!FastThreadLocalThread.willCleanupFastThreadLocals(Thread.currentThread())) {
162
163 return NO_MAGAZINE;
164 }
165 Magazine mag = new Magazine(AdaptivePoolingAllocator.this, false);
166 liveMagazines.add(mag);
167 return mag;
168 }
169 return NO_MAGAZINE;
170 }
171
172 @Override
173 protected void onRemoval(final Object value) throws Exception {
174 if (value != NO_MAGAZINE) {
175 liveMagazines.remove(value);
176 }
177 }
178 };
179 liveCachedMagazines = liveMagazines;
180 } else {
181 threadLocalMagazine = null;
182 liveCachedMagazines = null;
183 }
184 Magazine[] mags = new Magazine[INITIAL_MAGAZINES];
185 for (int i = 0; i < mags.length; i++) {
186 mags[i] = new Magazine(this);
187 }
188 magazines = mags;
189 }
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211 private static Queue<Chunk> createSharedChunkQueue() {
212 return PlatformDependent.newFixedMpmcQueue(CENTRAL_QUEUE_CAPACITY);
213 }
214
215 ByteBuf allocate(int size, int maxCapacity) {
216 return allocate(size, maxCapacity, Thread.currentThread(), null);
217 }
218
219 private AdaptiveByteBuf allocate(int size, int maxCapacity, Thread currentThread, AdaptiveByteBuf buf) {
220 if (size <= MAX_CHUNK_SIZE) {
221 int sizeBucket = AllocationStatistics.sizeBucket(size);
222 FastThreadLocal<Object> threadLocalMagazine = this.threadLocalMagazine;
223 if (threadLocalMagazine != null && currentThread instanceof FastThreadLocalThread) {
224 Object mag = threadLocalMagazine.get();
225 if (mag != NO_MAGAZINE) {
226 Magazine magazine = (Magazine) mag;
227 if (buf == null) {
228 buf = magazine.newBuffer();
229 }
230 boolean allocated = magazine.tryAllocate(size, sizeBucket, maxCapacity, buf);
231 assert allocated : "Allocation of threadLocalMagazine must always succeed";
232 return buf;
233 }
234 }
235 long threadId = currentThread.getId();
236 Magazine[] mags;
237 int expansions = 0;
238 do {
239 mags = magazines;
240 int mask = mags.length - 1;
241 int index = (int) (threadId & mask);
242 for (int i = 0, m = Integer.numberOfTrailingZeros(~mask); i < m; i++) {
243 Magazine mag = mags[index + i & mask];
244 if (buf == null) {
245 buf = mag.newBuffer();
246 }
247 if (mag.tryAllocate(size, sizeBucket, maxCapacity, buf)) {
248
249 return buf;
250 }
251 }
252 expansions++;
253 } while (expansions <= EXPANSION_ATTEMPTS && tryExpandMagazines(mags.length));
254 }
255
256
257 return allocateFallback(size, maxCapacity, currentThread, buf);
258 }
259
260 private AdaptiveByteBuf allocateFallback(int size, int maxCapacity, Thread currentThread, AdaptiveByteBuf buf) {
261
262 Magazine magazine;
263 if (buf != null) {
264 Chunk chunk = buf.chunk;
265 if (chunk == null || chunk == Magazine.MAGAZINE_FREED || (magazine = chunk.currentMagazine()) == null) {
266 magazine = getFallbackMagazine(currentThread);
267 }
268 } else {
269 magazine = getFallbackMagazine(currentThread);
270 buf = magazine.newBuffer();
271 }
272
273 AbstractByteBuf innerChunk = chunkAllocator.allocate(size, maxCapacity);
274 Chunk chunk = new Chunk(innerChunk, magazine, false);
275 try {
276 chunk.readInitInto(buf, size, maxCapacity);
277 } finally {
278
279
280
281 chunk.release();
282 }
283 return buf;
284 }
285
286 private Magazine getFallbackMagazine(Thread currentThread) {
287 Object tlMag;
288 FastThreadLocal<Object> threadLocalMagazine = this.threadLocalMagazine;
289 if (threadLocalMagazine != null &&
290 currentThread instanceof FastThreadLocalThread &&
291 (tlMag = threadLocalMagazine.get()) != NO_MAGAZINE) {
292 return (Magazine) tlMag;
293 }
294 Magazine[] mags = magazines;
295 return mags[(int) currentThread.getId() & mags.length - 1];
296 }
297
298
299
300
301 void allocate(int size, int maxCapacity, AdaptiveByteBuf into) {
302 AdaptiveByteBuf result = allocate(size, maxCapacity, Thread.currentThread(), into);
303 assert result == into: "Re-allocation created separate buffer instance";
304 }
305
306 long usedMemory() {
307 long sum = 0;
308 for (Chunk chunk : centralQueue) {
309 sum += chunk.capacity();
310 }
311 for (Magazine magazine : magazines) {
312 sum += magazine.usedMemory.get();
313 }
314 if (liveCachedMagazines != null) {
315 for (Magazine magazine : liveCachedMagazines) {
316 sum += magazine.usedMemory.get();
317 }
318 }
319 return sum;
320 }
321
322 private boolean tryExpandMagazines(int currentLength) {
323 if (currentLength >= MAX_STRIPES) {
324 return true;
325 }
326 final Magazine[] mags;
327 long writeLock = magazineExpandLock.tryWriteLock();
328 if (writeLock != 0) {
329 try {
330 mags = magazines;
331 if (mags.length >= MAX_STRIPES || mags.length > currentLength || freed) {
332 return true;
333 }
334 int preferredChunkSize = mags[0].sharedPrefChunkSize;
335 Magazine[] expanded = new Magazine[mags.length * 2];
336 for (int i = 0, l = expanded.length; i < l; i++) {
337 Magazine m = new Magazine(this);
338 m.localPrefChunkSize = preferredChunkSize;
339 m.sharedPrefChunkSize = preferredChunkSize;
340 expanded[i] = m;
341 }
342 magazines = expanded;
343 } finally {
344 magazineExpandLock.unlockWrite(writeLock);
345 }
346 for (Magazine magazine : mags) {
347 magazine.free();
348 }
349 }
350 return true;
351 }
352
353 private boolean offerToQueue(Chunk buffer) {
354 if (freed) {
355 return false;
356 }
357
358 assert buffer.allocatedBytes == 0;
359 assert buffer.magazine == null;
360
361 boolean isAdded = centralQueue.offer(buffer);
362 if (freed && isAdded) {
363
364 freeCentralQueue();
365 }
366 return isAdded;
367 }
368
369
370
371
372 @Override
373 protected void finalize() throws Throwable {
374 try {
375 super.finalize();
376 } finally {
377 free();
378 }
379 }
380
381 private void free() {
382 freed = true;
383 long stamp = magazineExpandLock.writeLock();
384 try {
385 Magazine[] mags = magazines;
386 for (Magazine magazine : mags) {
387 magazine.free();
388 }
389 } finally {
390 magazineExpandLock.unlockWrite(stamp);
391 }
392 freeCentralQueue();
393 }
394
395 private void freeCentralQueue() {
396 for (;;) {
397 Chunk chunk = centralQueue.poll();
398 if (chunk == null) {
399 break;
400 }
401 chunk.release();
402 }
403 }
404
405 static int sizeBucket(int size) {
406 return AllocationStatistics.sizeBucket(size);
407 }
408
409 @SuppressWarnings("checkstyle:finalclass")
410 private static class AllocationStatistics {
411 private static final int MIN_DATUM_TARGET = 1024;
412 private static final int MAX_DATUM_TARGET = 65534;
413 private static final int INIT_DATUM_TARGET = 9;
414 private static final int HISTO_MIN_BUCKET_SHIFT = 13;
415 private static final int HISTO_MAX_BUCKET_SHIFT = 20;
416 private static final int HISTO_BUCKET_COUNT = 1 + HISTO_MAX_BUCKET_SHIFT - HISTO_MIN_BUCKET_SHIFT;
417 private static final int HISTO_MAX_BUCKET_MASK = HISTO_BUCKET_COUNT - 1;
418 private static final int SIZE_MAX_MASK = MAX_CHUNK_SIZE - 1;
419
420 protected final AdaptivePoolingAllocator parent;
421 private final boolean shareable;
422 private final short[][] histos = {
423 new short[HISTO_BUCKET_COUNT], new short[HISTO_BUCKET_COUNT],
424 new short[HISTO_BUCKET_COUNT], new short[HISTO_BUCKET_COUNT],
425 };
426 private short[] histo = histos[0];
427 private final int[] sums = new int[HISTO_BUCKET_COUNT];
428
429 private int histoIndex;
430 private int datumCount;
431 private int datumTarget = INIT_DATUM_TARGET;
432 protected volatile int sharedPrefChunkSize = MIN_CHUNK_SIZE;
433 protected volatile int localPrefChunkSize = MIN_CHUNK_SIZE;
434
435 private AllocationStatistics(AdaptivePoolingAllocator parent, boolean shareable) {
436 this.parent = parent;
437 this.shareable = shareable;
438 }
439
440 protected void recordAllocationSize(int bucket) {
441 histo[bucket]++;
442 if (datumCount++ == datumTarget) {
443 rotateHistograms();
444 }
445 }
446
447 static int sizeBucket(int size) {
448 if (size == 0) {
449 return 0;
450 }
451
452
453
454
455 int normalizedSize = size - 1 >> HISTO_MIN_BUCKET_SHIFT & SIZE_MAX_MASK;
456 return Math.min(Integer.SIZE - Integer.numberOfLeadingZeros(normalizedSize), HISTO_MAX_BUCKET_MASK);
457 }
458
459 private void rotateHistograms() {
460 short[][] hs = histos;
461 for (int i = 0; i < HISTO_BUCKET_COUNT; i++) {
462 sums[i] = (hs[0][i] & 0xFFFF) + (hs[1][i] & 0xFFFF) + (hs[2][i] & 0xFFFF) + (hs[3][i] & 0xFFFF);
463 }
464 int sum = 0;
465 for (int count : sums) {
466 sum += count;
467 }
468 int targetPercentile = (int) (sum * 0.99);
469 int sizeBucket = 0;
470 for (; sizeBucket < sums.length; sizeBucket++) {
471 if (sums[sizeBucket] > targetPercentile) {
472 break;
473 }
474 targetPercentile -= sums[sizeBucket];
475 }
476 int percentileSize = 1 << sizeBucket + HISTO_MIN_BUCKET_SHIFT;
477 int prefChunkSize = Math.max(percentileSize * BUFS_PER_CHUNK, MIN_CHUNK_SIZE);
478 localPrefChunkSize = prefChunkSize;
479 if (shareable) {
480 for (Magazine mag : parent.magazines) {
481 prefChunkSize = Math.max(prefChunkSize, mag.localPrefChunkSize);
482 }
483 }
484 if (sharedPrefChunkSize != prefChunkSize) {
485
486 datumTarget = Math.max(datumTarget >> 1, MIN_DATUM_TARGET);
487 sharedPrefChunkSize = prefChunkSize;
488 } else {
489
490 datumTarget = Math.min(datumTarget << 1, MAX_DATUM_TARGET);
491 }
492
493 histoIndex = histoIndex + 1 & 3;
494 histo = histos[histoIndex];
495 datumCount = 0;
496 Arrays.fill(histo, (short) 0);
497 }
498
499
500
501
502
503
504
505
506
507 protected int preferredChunkSize() {
508 return sharedPrefChunkSize;
509 }
510 }
511
512 private static final class Magazine extends AllocationStatistics {
513 private static final AtomicReferenceFieldUpdater<Magazine, Chunk> NEXT_IN_LINE;
514 static {
515 NEXT_IN_LINE = AtomicReferenceFieldUpdater.newUpdater(Magazine.class, Chunk.class, "nextInLine");
516 }
517 private static final Chunk MAGAZINE_FREED = new Chunk();
518
519 private static final ObjectPool<AdaptiveByteBuf> EVENT_LOOP_LOCAL_BUFFER_POOL = ObjectPool.newPool(
520 new ObjectPool.ObjectCreator<AdaptiveByteBuf>() {
521 @Override
522 public AdaptiveByteBuf newObject(ObjectPool.Handle<AdaptiveByteBuf> handle) {
523 return new AdaptiveByteBuf(handle);
524 }
525 });
526
527 private Chunk current;
528 @SuppressWarnings("unused")
529 private volatile Chunk nextInLine;
530 private final AtomicLong usedMemory;
531 private final StampedLock allocationLock;
532 private final Queue<AdaptiveByteBuf> bufferQueue;
533 private final ObjectPool.Handle<AdaptiveByteBuf> handle;
534
535 Magazine(AdaptivePoolingAllocator parent) {
536 this(parent, true);
537 }
538
539 Magazine(AdaptivePoolingAllocator parent, boolean shareable) {
540 super(parent, shareable);
541
542 if (shareable) {
543
544 allocationLock = new StampedLock();
545 bufferQueue = PlatformDependent.newFixedMpmcQueue(MAGAZINE_BUFFER_QUEUE_CAPACITY);
546 handle = new ObjectPool.Handle<AdaptiveByteBuf>() {
547 @Override
548 public void recycle(AdaptiveByteBuf self) {
549 bufferQueue.offer(self);
550 }
551 };
552 } else {
553 allocationLock = null;
554 bufferQueue = null;
555 handle = null;
556 }
557 usedMemory = new AtomicLong();
558 }
559
560 public boolean tryAllocate(int size, int sizeBucket, int maxCapacity, AdaptiveByteBuf buf) {
561 if (allocationLock == null) {
562
563 return allocate(size, sizeBucket, maxCapacity, buf);
564 }
565
566
567 long writeLock = allocationLock.tryWriteLock();
568 if (writeLock != 0) {
569 try {
570 return allocate(size, sizeBucket, maxCapacity, buf);
571 } finally {
572 allocationLock.unlockWrite(writeLock);
573 }
574 }
575 return allocateWithoutLock(size, maxCapacity, buf);
576 }
577
578 private boolean allocateWithoutLock(int size, int maxCapacity, AdaptiveByteBuf buf) {
579 Chunk curr = NEXT_IN_LINE.getAndSet(this, null);
580 if (curr == MAGAZINE_FREED) {
581
582 restoreMagazineFreed();
583 return false;
584 }
585 if (curr == null) {
586 curr = parent.centralQueue.poll();
587 if (curr == null) {
588 return false;
589 }
590 curr.attachToMagazine(this);
591 }
592 boolean allocated = false;
593 if (curr.remainingCapacity() >= size) {
594 curr.readInitInto(buf, size, maxCapacity);
595 allocated = true;
596 }
597 try {
598 if (curr.remainingCapacity() >= RETIRE_CAPACITY) {
599 transferToNextInLineOrRelease(curr);
600 curr = null;
601 }
602 } finally {
603 if (curr != null) {
604 curr.release();
605 }
606 }
607 return allocated;
608 }
609
610 private boolean allocate(int size, int sizeBucket, int maxCapacity, AdaptiveByteBuf buf) {
611 recordAllocationSize(sizeBucket);
612 Chunk curr = current;
613 if (curr != null) {
614
615 if (curr.remainingCapacity() > size) {
616 curr.readInitInto(buf, size, maxCapacity);
617
618 return true;
619 }
620
621
622
623 current = null;
624 if (curr.remainingCapacity() == size) {
625 try {
626 curr.readInitInto(buf, size, maxCapacity);
627 return true;
628 } finally {
629 curr.release();
630 }
631 }
632
633
634 if (curr.remainingCapacity() < RETIRE_CAPACITY) {
635 curr.release();
636 } else {
637
638
639 transferToNextInLineOrRelease(curr);
640 }
641 }
642
643 assert current == null;
644
645
646
647
648
649
650
651 curr = NEXT_IN_LINE.getAndSet(this, null);
652 if (curr != null) {
653 if (curr == MAGAZINE_FREED) {
654
655 restoreMagazineFreed();
656 return false;
657 }
658
659 if (curr.remainingCapacity() > size) {
660
661 curr.readInitInto(buf, size, maxCapacity);
662 current = curr;
663 return true;
664 }
665
666 if (curr.remainingCapacity() == size) {
667
668
669 try {
670 curr.readInitInto(buf, size, maxCapacity);
671 return true;
672 } finally {
673
674
675 curr.release();
676 }
677 } else {
678
679 curr.release();
680 }
681 }
682
683
684 curr = parent.centralQueue.poll();
685 if (curr == null) {
686 curr = newChunkAllocation(size);
687 } else {
688 curr.attachToMagazine(this);
689
690 if (curr.remainingCapacity() < size) {
691
692 if (curr.remainingCapacity() < RETIRE_CAPACITY) {
693 curr.release();
694 } else {
695
696
697 transferToNextInLineOrRelease(curr);
698 }
699 curr = newChunkAllocation(size);
700 }
701 }
702
703 current = curr;
704 try {
705 assert current.remainingCapacity() >= size;
706 if (curr.remainingCapacity() > size) {
707 curr.readInitInto(buf, size, maxCapacity);
708 curr = null;
709 } else {
710 curr.readInitInto(buf, size, maxCapacity);
711 }
712 } finally {
713 if (curr != null) {
714
715
716 curr.release();
717 current = null;
718 }
719 }
720 return true;
721 }
722
723 private void restoreMagazineFreed() {
724 Chunk next = NEXT_IN_LINE.getAndSet(this, MAGAZINE_FREED);
725 if (next != null && next != MAGAZINE_FREED) {
726 next.release();
727 }
728 }
729
730 private void transferToNextInLineOrRelease(Chunk chunk) {
731 if (NEXT_IN_LINE.compareAndSet(this, null, chunk)) {
732 return;
733 }
734
735 Chunk nextChunk = NEXT_IN_LINE.get(this);
736 if (nextChunk != null && nextChunk != MAGAZINE_FREED
737 && chunk.remainingCapacity() > nextChunk.remainingCapacity()) {
738 if (NEXT_IN_LINE.compareAndSet(this, nextChunk, chunk)) {
739 nextChunk.release();
740 return;
741 }
742 }
743
744
745
746
747 chunk.release();
748 }
749
750 private Chunk newChunkAllocation(int promptingSize) {
751 int size = Math.max(promptingSize * BUFS_PER_CHUNK, preferredChunkSize());
752 int minChunks = size / MIN_CHUNK_SIZE;
753 if (MIN_CHUNK_SIZE * minChunks < size) {
754
755
756
757
758 size = MIN_CHUNK_SIZE * (1 + minChunks);
759 }
760 ChunkAllocator chunkAllocator = parent.chunkAllocator;
761 return new Chunk(chunkAllocator.allocate(size, size), this, true);
762 }
763
764 boolean trySetNextInLine(Chunk chunk) {
765 return NEXT_IN_LINE.compareAndSet(this, null, chunk);
766 }
767
768 void free() {
769
770 restoreMagazineFreed();
771 long stamp = allocationLock.writeLock();
772 try {
773 if (current != null) {
774 current.release();
775 current = null;
776 }
777 } finally {
778 allocationLock.unlockWrite(stamp);
779 }
780 }
781
782 public AdaptiveByteBuf newBuffer() {
783 AdaptiveByteBuf buf;
784 if (handle == null) {
785 buf = EVENT_LOOP_LOCAL_BUFFER_POOL.get();
786 } else {
787 buf = bufferQueue.poll();
788 if (buf == null) {
789 buf = new AdaptiveByteBuf(handle);
790 }
791 }
792 buf.resetRefCnt();
793 buf.discardMarks();
794 return buf;
795 }
796 }
797
798 private static final class Chunk implements ReferenceCounted {
799
800 private final AbstractByteBuf delegate;
801 private Magazine magazine;
802 private final AdaptivePoolingAllocator allocator;
803 private final int capacity;
804 private final boolean pooled;
805 private int allocatedBytes;
806 private static final long REFCNT_FIELD_OFFSET =
807 ReferenceCountUpdater.getUnsafeOffset(Chunk.class, "refCnt");
808 private static final AtomicIntegerFieldUpdater<Chunk> AIF_UPDATER =
809 AtomicIntegerFieldUpdater.newUpdater(Chunk.class, "refCnt");
810
811 private static final ReferenceCountUpdater<Chunk> updater =
812 new ReferenceCountUpdater<Chunk>() {
813 @Override
814 protected AtomicIntegerFieldUpdater<Chunk> updater() {
815 return AIF_UPDATER;
816 }
817 @Override
818 protected long unsafeOffset() {
819 return REFCNT_FIELD_OFFSET;
820 }
821 };
822
823
824 @SuppressWarnings({"unused", "FieldMayBeFinal"})
825 private volatile int refCnt;
826
827 Chunk() {
828
829 delegate = null;
830 magazine = null;
831 allocator = null;
832 capacity = 0;
833 pooled = false;
834 }
835
836 Chunk(AbstractByteBuf delegate, Magazine magazine, boolean pooled) {
837 this.delegate = delegate;
838 this.pooled = pooled;
839 capacity = delegate.capacity();
840 updater.setInitialValue(this);
841 allocator = magazine.parent;
842 attachToMagazine(magazine);
843 }
844
845 Magazine currentMagazine() {
846 return magazine;
847 }
848
849 void detachFromMagazine() {
850 if (magazine != null) {
851 magazine.usedMemory.getAndAdd(-capacity);
852 magazine = null;
853 }
854 }
855
856 void attachToMagazine(Magazine magazine) {
857 assert this.magazine == null;
858 this.magazine = magazine;
859 magazine.usedMemory.getAndAdd(capacity);
860 }
861
862 @Override
863 public Chunk touch(Object hint) {
864 return this;
865 }
866
867 @Override
868 public int refCnt() {
869 return updater.refCnt(this);
870 }
871
872 @Override
873 public Chunk retain() {
874 return updater.retain(this);
875 }
876
877 @Override
878 public Chunk retain(int increment) {
879 return updater.retain(this, increment);
880 }
881
882 @Override
883 public Chunk touch() {
884 return this;
885 }
886
887 @Override
888 public boolean release() {
889 if (updater.release(this)) {
890 deallocate();
891 return true;
892 }
893 return false;
894 }
895
896 @Override
897 public boolean release(int decrement) {
898 if (updater.release(this, decrement)) {
899 deallocate();
900 return true;
901 }
902 return false;
903 }
904
905 private void deallocate() {
906 Magazine mag = magazine;
907 AdaptivePoolingAllocator parent = mag.parent;
908 int chunkSize = mag.preferredChunkSize();
909 int memSize = delegate.capacity();
910 if (!pooled || shouldReleaseSuboptimalChunkSize(memSize, chunkSize)) {
911
912
913 detachFromMagazine();
914 delegate.release();
915 } else {
916 updater.resetRefCnt(this);
917 delegate.setIndex(0, 0);
918 allocatedBytes = 0;
919 if (!mag.trySetNextInLine(this)) {
920
921 detachFromMagazine();
922 if (!parent.offerToQueue(this)) {
923
924
925 boolean released = updater.release(this);
926 delegate.release();
927 assert released;
928 }
929 }
930 }
931 }
932
933 private static boolean shouldReleaseSuboptimalChunkSize(int givenSize, int preferredSize) {
934 int givenChunks = givenSize / MIN_CHUNK_SIZE;
935 int preferredChunks = preferredSize / MIN_CHUNK_SIZE;
936 int deviation = Math.abs(givenChunks - preferredChunks);
937
938
939 return deviation != 0 &&
940 ThreadLocalRandom.current().nextDouble() * 20.0 < deviation;
941 }
942
943 public void readInitInto(AdaptiveByteBuf buf, int size, int maxCapacity) {
944 int startIndex = allocatedBytes;
945 allocatedBytes = startIndex + size;
946 Chunk chunk = this;
947 chunk.retain();
948 try {
949 buf.init(delegate, chunk, 0, 0, startIndex, size, maxCapacity);
950 chunk = null;
951 } finally {
952 if (chunk != null) {
953
954
955
956 allocatedBytes = startIndex;
957 chunk.release();
958 }
959 }
960 }
961
962 public int remainingCapacity() {
963 return capacity - allocatedBytes;
964 }
965
966 public int capacity() {
967 return capacity;
968 }
969 }
970
971 static final class AdaptiveByteBuf extends AbstractReferenceCountedByteBuf {
972
973 private final ObjectPool.Handle<AdaptiveByteBuf> handle;
974
975 private int adjustment;
976 private AbstractByteBuf rootParent;
977 Chunk chunk;
978 private int length;
979 private ByteBuffer tmpNioBuf;
980 private boolean hasArray;
981 private boolean hasMemoryAddress;
982
983 AdaptiveByteBuf(ObjectPool.Handle<AdaptiveByteBuf> recyclerHandle) {
984 super(0);
985 handle = ObjectUtil.checkNotNull(recyclerHandle, "recyclerHandle");
986 }
987
988 void init(AbstractByteBuf unwrapped, Chunk wrapped, int readerIndex, int writerIndex,
989 int adjustment, int capacity, int maxCapacity) {
990 this.adjustment = adjustment;
991 chunk = wrapped;
992 length = capacity;
993 maxCapacity(maxCapacity);
994 setIndex0(readerIndex, writerIndex);
995 hasArray = unwrapped.hasArray();
996 hasMemoryAddress = unwrapped.hasMemoryAddress();
997 rootParent = unwrapped;
998 tmpNioBuf = null;
999 }
1000
1001 private AbstractByteBuf rootParent() {
1002 final AbstractByteBuf rootParent = this.rootParent;
1003 if (rootParent != null) {
1004 return rootParent;
1005 }
1006 throw new IllegalReferenceCountException();
1007 }
1008
1009 @Override
1010 public int capacity() {
1011 return length;
1012 }
1013
1014 @Override
1015 public ByteBuf capacity(int newCapacity) {
1016 if (newCapacity == capacity()) {
1017 ensureAccessible();
1018 return this;
1019 }
1020 checkNewCapacity(newCapacity);
1021 if (newCapacity < capacity()) {
1022 length = newCapacity;
1023 setIndex0(Math.min(readerIndex(), newCapacity), Math.min(writerIndex(), newCapacity));
1024 return this;
1025 }
1026
1027
1028 Chunk chunk = this.chunk;
1029 AdaptivePoolingAllocator allocator = chunk.allocator;
1030 int readerIndex = this.readerIndex;
1031 int writerIndex = this.writerIndex;
1032 int baseOldRootIndex = adjustment;
1033 int oldCapacity = length;
1034 AbstractByteBuf oldRoot = rootParent();
1035 allocator.allocate(newCapacity, maxCapacity(), this);
1036 oldRoot.getBytes(baseOldRootIndex, this, 0, oldCapacity);
1037 chunk.release();
1038 this.readerIndex = readerIndex;
1039 this.writerIndex = writerIndex;
1040 return this;
1041 }
1042
1043 @Override
1044 public ByteBufAllocator alloc() {
1045 return rootParent().alloc();
1046 }
1047
1048 @Override
1049 public ByteOrder order() {
1050 return rootParent().order();
1051 }
1052
1053 @Override
1054 public ByteBuf unwrap() {
1055 return null;
1056 }
1057
1058 @Override
1059 public boolean isDirect() {
1060 return rootParent().isDirect();
1061 }
1062
1063 @Override
1064 public int arrayOffset() {
1065 return idx(rootParent().arrayOffset());
1066 }
1067
1068 @Override
1069 public boolean hasMemoryAddress() {
1070 return hasMemoryAddress;
1071 }
1072
1073 @Override
1074 public long memoryAddress() {
1075 ensureAccessible();
1076 return rootParent().memoryAddress() + adjustment;
1077 }
1078
1079 @Override
1080 public ByteBuffer nioBuffer(int index, int length) {
1081 checkIndex(index, length);
1082 return rootParent().nioBuffer(idx(index), length);
1083 }
1084
1085 @Override
1086 public ByteBuffer internalNioBuffer(int index, int length) {
1087 checkIndex(index, length);
1088 return (ByteBuffer) internalNioBuffer().position(index).limit(index + length);
1089 }
1090
1091 private ByteBuffer internalNioBuffer() {
1092 if (tmpNioBuf == null) {
1093 tmpNioBuf = rootParent().internalNioBuffer(adjustment, length).slice();
1094 }
1095 return (ByteBuffer) tmpNioBuf.clear();
1096 }
1097
1098 @Override
1099 public ByteBuffer[] nioBuffers(int index, int length) {
1100 checkIndex(index, length);
1101 return rootParent().nioBuffers(idx(index), length);
1102 }
1103
1104 @Override
1105 public boolean hasArray() {
1106 return hasArray;
1107 }
1108
1109 @Override
1110 public byte[] array() {
1111 ensureAccessible();
1112 return rootParent().array();
1113 }
1114
1115 @Override
1116 public ByteBuf copy(int index, int length) {
1117 checkIndex(index, length);
1118 return rootParent().copy(idx(index), length);
1119 }
1120
1121 @Override
1122 public int nioBufferCount() {
1123 return rootParent().nioBufferCount();
1124 }
1125
1126 @Override
1127 protected byte _getByte(int index) {
1128 return rootParent()._getByte(idx(index));
1129 }
1130
1131 @Override
1132 protected short _getShort(int index) {
1133 return rootParent()._getShort(idx(index));
1134 }
1135
1136 @Override
1137 protected short _getShortLE(int index) {
1138 return rootParent()._getShortLE(idx(index));
1139 }
1140
1141 @Override
1142 protected int _getUnsignedMedium(int index) {
1143 return rootParent()._getUnsignedMedium(idx(index));
1144 }
1145
1146 @Override
1147 protected int _getUnsignedMediumLE(int index) {
1148 return rootParent()._getUnsignedMediumLE(idx(index));
1149 }
1150
1151 @Override
1152 protected int _getInt(int index) {
1153 return rootParent()._getInt(idx(index));
1154 }
1155
1156 @Override
1157 protected int _getIntLE(int index) {
1158 return rootParent()._getIntLE(idx(index));
1159 }
1160
1161 @Override
1162 protected long _getLong(int index) {
1163 return rootParent()._getLong(idx(index));
1164 }
1165
1166 @Override
1167 protected long _getLongLE(int index) {
1168 return rootParent()._getLongLE(idx(index));
1169 }
1170
1171 @Override
1172 public ByteBuf getBytes(int index, ByteBuf dst, int dstIndex, int length) {
1173 checkIndex(index, length);
1174 rootParent().getBytes(idx(index), dst, dstIndex, length);
1175 return this;
1176 }
1177
1178 @Override
1179 public ByteBuf getBytes(int index, byte[] dst, int dstIndex, int length) {
1180 checkIndex(index, length);
1181 rootParent().getBytes(idx(index), dst, dstIndex, length);
1182 return this;
1183 }
1184
1185 @Override
1186 public ByteBuf getBytes(int index, ByteBuffer dst) {
1187 checkIndex(index, dst.remaining());
1188 rootParent().getBytes(idx(index), dst);
1189 return this;
1190 }
1191
1192 @Override
1193 protected void _setByte(int index, int value) {
1194 rootParent()._setByte(idx(index), value);
1195 }
1196
1197 @Override
1198 protected void _setShort(int index, int value) {
1199 rootParent()._setShort(idx(index), value);
1200 }
1201
1202 @Override
1203 protected void _setShortLE(int index, int value) {
1204 rootParent()._setShortLE(idx(index), value);
1205 }
1206
1207 @Override
1208 protected void _setMedium(int index, int value) {
1209 rootParent()._setMedium(idx(index), value);
1210 }
1211
1212 @Override
1213 protected void _setMediumLE(int index, int value) {
1214 rootParent()._setMediumLE(idx(index), value);
1215 }
1216
1217 @Override
1218 protected void _setInt(int index, int value) {
1219 rootParent()._setInt(idx(index), value);
1220 }
1221
1222 @Override
1223 protected void _setIntLE(int index, int value) {
1224 rootParent()._setIntLE(idx(index), value);
1225 }
1226
1227 @Override
1228 protected void _setLong(int index, long value) {
1229 rootParent()._setLong(idx(index), value);
1230 }
1231
1232 @Override
1233 protected void _setLongLE(int index, long value) {
1234 rootParent().setLongLE(idx(index), value);
1235 }
1236
1237 @Override
1238 public ByteBuf setBytes(int index, byte[] src, int srcIndex, int length) {
1239 checkIndex(index, length);
1240 rootParent().setBytes(idx(index), src, srcIndex, length);
1241 return this;
1242 }
1243
1244 @Override
1245 public ByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length) {
1246 checkIndex(index, length);
1247 rootParent().setBytes(idx(index), src, srcIndex, length);
1248 return this;
1249 }
1250
1251 @Override
1252 public ByteBuf setBytes(int index, ByteBuffer src) {
1253 checkIndex(index, src.remaining());
1254 rootParent().setBytes(idx(index), src);
1255 return this;
1256 }
1257
1258 @Override
1259 public ByteBuf getBytes(int index, OutputStream out, int length)
1260 throws IOException {
1261 checkIndex(index, length);
1262 if (length != 0) {
1263 ByteBufUtil.readBytes(alloc(), internalNioBuffer().duplicate(), index, length, out);
1264 }
1265 return this;
1266 }
1267
1268 @Override
1269 public int getBytes(int index, GatheringByteChannel out, int length)
1270 throws IOException {
1271 return out.write(internalNioBuffer(index, length).duplicate());
1272 }
1273
1274 @Override
1275 public int getBytes(int index, FileChannel out, long position, int length)
1276 throws IOException {
1277 return out.write(internalNioBuffer(index, length).duplicate(), position);
1278 }
1279
1280 @Override
1281 public int setBytes(int index, InputStream in, int length)
1282 throws IOException {
1283 checkIndex(index, length);
1284 final AbstractByteBuf rootParent = rootParent();
1285 if (rootParent.hasArray()) {
1286 return rootParent.setBytes(idx(index), in, length);
1287 }
1288 byte[] tmp = ByteBufUtil.threadLocalTempArray(length);
1289 int readBytes = in.read(tmp, 0, length);
1290 if (readBytes <= 0) {
1291 return readBytes;
1292 }
1293 setBytes(index, tmp, 0, readBytes);
1294 return readBytes;
1295 }
1296
1297 @Override
1298 public int setBytes(int index, ScatteringByteChannel in, int length)
1299 throws IOException {
1300 try {
1301 return in.read(internalNioBuffer(index, length).duplicate());
1302 } catch (ClosedChannelException ignored) {
1303 return -1;
1304 }
1305 }
1306
1307 @Override
1308 public int setBytes(int index, FileChannel in, long position, int length)
1309 throws IOException {
1310 try {
1311 return in.read(internalNioBuffer(index, length).duplicate(), position);
1312 } catch (ClosedChannelException ignored) {
1313 return -1;
1314 }
1315 }
1316
1317 @Override
1318 public int forEachByte(int index, int length, ByteProcessor processor) {
1319 checkIndex(index, length);
1320 int ret = rootParent().forEachByte(idx(index), length, processor);
1321 return forEachResult(ret);
1322 }
1323
1324 @Override
1325 public int forEachByteDesc(int index, int length, ByteProcessor processor) {
1326 checkIndex(index, length);
1327 int ret = rootParent().forEachByteDesc(idx(index), length, processor);
1328 return forEachResult(ret);
1329 }
1330
1331 private int forEachResult(int ret) {
1332 if (ret < adjustment) {
1333 return -1;
1334 }
1335 return ret - adjustment;
1336 }
1337
1338 @Override
1339 public boolean isContiguous() {
1340 return rootParent().isContiguous();
1341 }
1342
1343 private int idx(int index) {
1344 return index + adjustment;
1345 }
1346
1347 @Override
1348 protected void deallocate() {
1349 if (chunk != null) {
1350 chunk.release();
1351 }
1352 tmpNioBuf = null;
1353 chunk = null;
1354 rootParent = null;
1355 if (handle instanceof EnhancedHandle) {
1356 EnhancedHandle<AdaptiveByteBuf> enhancedHandle = (EnhancedHandle<AdaptiveByteBuf>) handle;
1357 enhancedHandle.unguardedRecycle(this);
1358 } else {
1359 handle.recycle(this);
1360 }
1361 }
1362 }
1363
1364
1365
1366
1367 interface ChunkAllocator {
1368
1369
1370
1371
1372
1373
1374 AbstractByteBuf allocate(int initialCapacity, int maxCapacity);
1375 }
1376 }