View Javadoc
1   /*
2    * Copyright 2022 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
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   * An auto-tuning pooling allocator, that follows an anti-generational hypothesis.
55   * <p>
56   * The allocator is organized into a list of Magazines, and each magazine has a chunk-buffer that they allocate buffers
57   * from.
58   * <p>
59   * The magazines hold the mutexes that ensure the thread-safety of the allocator, and each thread picks a magazine
60   * based on the id of the thread. This spreads the contention of multi-threaded access across the magazines.
61   * If contention is detected above a certain threshold, the number of magazines are increased in response to the
62   * contention.
63   * <p>
64   * The magazines maintain histograms of the sizes of the allocations they do. The histograms are used to compute the
65   * preferred chunk size. The preferred chunk size is one that is big enough to service 10 allocations of the
66   * 99-percentile size. This way, the chunk size is adapted to the allocation patterns.
67   * <p>
68   * Computing the preferred chunk size is a somewhat expensive operation. Therefore, the frequency with which this is
69   * done, is also adapted to the allocation pattern. If a newly computed preferred chunk is the same as the previous
70   * preferred chunk size, then the frequency is reduced. Otherwise, the frequency is increased.
71   * <p>
72   * This allows the allocator to quickly respond to changes in the application workload,
73   * without suffering undue overhead from maintaining its statistics.
74   * <p>
75   * Since magazines are "relatively thread-local", the allocator has a central queue that allow excess chunks from any
76   * magazine, to be shared with other magazines.
77   * The {@link #createSharedChunkQueue()} method can be overridden to customize this queue.
78   */
79  @UnstableApi
80  final class AdaptivePoolingAllocator {
81  
82      enum MagazineCaching {
83          EventLoopThreads,
84          FastThreadLocalThreads,
85          None
86      }
87  
88      /**
89       * The 128 KiB minimum chunk size is chosen to encourage the system allocator to delegate to mmap for chunk
90       * allocations. For instance, glibc will do this.
91       * This pushes any fragmentation from chunk size deviations off physical memory, onto virtual memory,
92       * which is a much, much larger space. Chunks are also allocated in whole multiples of the minimum
93       * chunk size, which itself is a whole multiple of popular page sizes like 4 KiB, 16 KiB, and 64 KiB.
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; // For large buffers, aim to have about this many buffers per chunk.
101 
102     /**
103      * The maximum size of a pooled chunk, in bytes. Allocations bigger than this will never be pooled.
104      * <p>
105      * This number is 10 MiB, and is derived from the limitations of internal histograms.
106      */
107     private static final int MAX_CHUNK_SIZE =
108             BUFS_PER_CHUNK * (1 << AllocationStatistics.HISTO_MAX_BUCKET_SHIFT); // 10 MiB.
109 
110     /**
111      * The capacity if the central queue that allow chunks to be shared across magazines.
112      * The default size is {@link NettyRuntime#availableProcessors()},
113      * and the maximum number of magazines is twice this.
114      * <p>
115      * This means the maximum amount of memory that we can have allocated-but-not-in-use is
116      * 5 * {@link NettyRuntime#availableProcessors()} * {@link #MAX_CHUNK_SIZE} bytes.
117      */
118     private static final int CENTRAL_QUEUE_CAPACITY = Math.max(2, SystemPropertyUtil.getInt(
119             "io.netty.allocator.centralQueueCapacity", NettyRuntime.availableProcessors()));
120 
121     /**
122      * The capacity if the magazine local buffer queue. This queue just pools the outer ByteBuf instance and not
123      * the actual memory and so helps to reduce GC pressure.
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                             // To prevent potential leak, we will not use thread-local magazine.
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      * Create a thread-safe multi-producer, multi-consumer queue to hold chunks that spill over from the
193      * internal Magazines.
194      * <p>
195      * Each Magazine can only hold two chunks at any one time: the chunk it currently allocates from,
196      * and the next-in-line chunk which will be used for allocation once the current one has been used up.
197      * This queue will be used by magazines to share any excess chunks they allocate, so that they don't need to
198      * allocate new chunks when their current and next-in-line chunks have both been used up.
199      * <p>
200      * The simplest implementation of this method is to return a new {@link ConcurrentLinkedQueue}.
201      * However, the {@code CLQ} is unbounded, and this means there's no limit to how many chunks can be cached in this
202      * queue.
203      * <p>
204      * Each chunk in this queue can be up to {@link #MAX_CHUNK_SIZE} in size, so it is recommended to use a bounded
205      * queue to limit the maximum memory usage.
206      * <p>
207      * The default implementation will create a bounded queue with a capacity of {@link #CENTRAL_QUEUE_CAPACITY}.
208      *
209      * @return A new multi-producer, multi-consumer queue.
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); // Compute outside of Magazine lock for better ILP.
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                         // Was able to allocate.
249                         return buf;
250                     }
251                 }
252                 expansions++;
253             } while (expansions <= EXPANSION_ATTEMPTS && tryExpandMagazines(mags.length));
254         }
255 
256         // The magazines failed us, or the buffer is too big to be pooled.
257         return allocateFallback(size, maxCapacity, currentThread, buf);
258     }
259 
260     private AdaptiveByteBuf allocateFallback(int size, int maxCapacity, Thread currentThread, AdaptiveByteBuf buf) {
261         // If we don't already have a buffer, obtain one from the most conveniently available magazine.
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         // Create a one-off chunk for this allocation.
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             // As the chunk is an one-off we need to always call release explicitly as readInitInto(...)
279             // will take care of retain once when successful. Once The AdaptiveByteBuf is released it will
280             // completely release the Chunk and so the contained innerChunk.
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      * Allocate into the given buffer. Used by {@link AdaptiveByteBuf#capacity(int)}.
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         // The Buffer should not be used anymore, let's add an assert to so we guard against bugs in the future.
358         assert buffer.allocatedBytes == 0;
359         assert buffer.magazine == null;
360 
361         boolean isAdded = centralQueue.offer(buffer);
362         if (freed && isAdded) {
363             // Help to free the centralQueue.
364             freeCentralQueue();
365         }
366         return isAdded;
367     }
368 
369     // Ensure that we release all previous pooled resources when this object is finalized. This is needed as otherwise
370     // we might end up with leaks. While these leaks are usually harmless in reality it would still at least be
371     // very confusing for users.
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") // Checkstyle mistakenly believes this class should be final.
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; // Smallest bucket is 1 << 13 = 8192 bytes in size.
415         private static final int HISTO_MAX_BUCKET_SHIFT = 20; // Biggest bucket is 1 << 20 = 1 MiB bytes in size.
416         private static final int HISTO_BUCKET_COUNT = 1 + HISTO_MAX_BUCKET_SHIFT - HISTO_MIN_BUCKET_SHIFT; // 8 buckets.
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             // Minimum chunk size is 128 KiB. We'll only make bigger chunks if the 99-percentile is 16 KiB or greater,
452             // so we truncate and roll up the bottom part of the histogram to 8 KiB.
453             // The upper size band is 1 MiB, and that gives us exactly 8 size buckets,
454             // which is a magical number for JIT optimisations.
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                 // Preferred chunk size changed. Increase check frequency.
486                 datumTarget = Math.max(datumTarget >> 1, MIN_DATUM_TARGET);
487                 sharedPrefChunkSize = prefChunkSize;
488             } else {
489                 // Preferred chunk size did not change. Check less often.
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          * Get the preferred chunk size, based on statistics from the {@linkplain #recordAllocationSize(int) recorded}
501          * allocation sizes.
502          * <p>
503          * This method must be thread-safe.
504          *
505          * @return The currently preferred chunk allocation size.
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") // updated via NEXT_IN_LINE
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                 // We only need the StampedLock if this Magazine will be shared across threads.
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                 // This magazine is not shared across threads, just allocate directly.
563                 return allocate(size, sizeBucket, maxCapacity, buf);
564             }
565 
566             // Try to retrieve the lock and if successful allocate.
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                 // Allocation raced with a stripe-resize that freed this magazine.
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                 // We have a Chunk that has some space left.
615                 if (curr.remainingCapacity() > size) {
616                     curr.readInitInto(buf, size, maxCapacity);
617                     // We still have some bytes left that we can use for the next allocation, just early return.
618                     return true;
619                 }
620 
621                 // At this point we know that this will be the last time current will be used, so directly set it to
622                 // null and release it once we are done.
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                 // Check if we either retain the chunk in the nextInLine cache or releasing it.
634                 if (curr.remainingCapacity() < RETIRE_CAPACITY) {
635                     curr.release();
636                 } else {
637                     // See if it makes sense to transfer the Chunk to the nextInLine cache for later usage.
638                     // This method will release curr if this is not the case
639                     transferToNextInLineOrRelease(curr);
640                 }
641             }
642 
643             assert current == null;
644             // The fast-path for allocations did not work.
645             //
646             // Try to fetch the next "Magazine local" Chunk first, if this this fails as we don't have
647             // one setup we will poll our centralQueue. If this fails as well we will just allocate a new Chunk.
648             //
649             // In any case we will store the Chunk as the current so it will be used again for the next allocation and
650             // so be "reserved" by this Magazine for exclusive usage.
651             curr = NEXT_IN_LINE.getAndSet(this, null);
652             if (curr != null) {
653                 if (curr == MAGAZINE_FREED) {
654                     // Allocation raced with a stripe-resize that freed this magazine.
655                     restoreMagazineFreed();
656                     return false;
657                 }
658 
659                 if (curr.remainingCapacity() > size) {
660                     // We have a Chunk that has some space left.
661                     curr.readInitInto(buf, size, maxCapacity);
662                     current = curr;
663                     return true;
664                 }
665 
666                 if (curr.remainingCapacity() == size) {
667                     // At this point we know that this will be the last time curr will be used, so directly set it to
668                     // null and release it once we are done.
669                     try {
670                         curr.readInitInto(buf, size, maxCapacity);
671                         return true;
672                     } finally {
673                         // Release in a finally block so even if readInitInto(...) would throw we would still correctly
674                         // release the current chunk before null it out.
675                         curr.release();
676                     }
677                 } else {
678                     // Release it as it's too small.
679                     curr.release();
680                 }
681             }
682 
683             // Now try to poll from the central queue first
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                     // Check if we either retain the chunk in the nextInLine cache or releasing it.
692                     if (curr.remainingCapacity() < RETIRE_CAPACITY) {
693                         curr.release();
694                     } else {
695                         // See if it makes sense to transfer the Chunk to the nextInLine cache for later usage.
696                         // This method will release curr if this is not the case
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                     // Release in a finally block so even if readInitInto(...) would throw we would still correctly
715                     // release the current chunk before null it out.
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(); // A chunk snuck in through a race. Release it after restoring MAGAZINE_FREED state.
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             // Next-in-line is occupied. We don't try to add it to the central queue yet as it might still be used
744             // by some buffers and so is attached to a Magazine.
745             // Once a Chunk is completely released by Chunk.release() it will try to move itself to the queue
746             // as last resort.
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                 // Round up to nearest whole MIN_CHUNK_SIZE unit. The MIN_CHUNK_SIZE is an even multiple of many
755                 // popular small page sizes, like 4k, 16k, and 64k, which makes it easier for the system allocator
756                 // to manage the memory in terms of whole pages. This reduces memory fragmentation,
757                 // but without the potentially high overhead that power-of-2 chunk sizes would bring.
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             // Release the current Chunk and the next that was stored for later usage.
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         // Value might not equal "real" reference count, all access should be via the updater
824         @SuppressWarnings({"unused", "FieldMayBeFinal"})
825         private volatile int refCnt;
826 
827         Chunk() {
828             // Constructor only used by the MAGAZINE_FREED sentinel.
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                 // Drop the chunk if the parent allocator is closed,
912                 // or if the chunk deviates too much from the preferred chunk size.
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                     // As this Chunk does not belong to the mag anymore we need to decrease the used memory .
921                     detachFromMagazine();
922                     if (!parent.offerToQueue(this)) {
923                         // The central queue is full. Ensure we release again as we previously did use resetRefCnt()
924                         // which did increase the reference count by 1.
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             // Retire chunks with a 5% probability per unit of MIN_CHUNK_SIZE deviation from preference.
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                     // If chunk is not null we know that buf.init(...) failed and so we need to manually release
954                     // the chunk again as we retained it before calling buf.init(...). Beside this we also need to
955                     // restore the old allocatedBytes value.
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             // Reallocation required.
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      * The strategy for how {@link AdaptivePoolingAllocator} should allocate chunk buffers.
1366      */
1367     interface ChunkAllocator {
1368         /**
1369          * Allocate a buffer for a chunk. This can be any kind of {@link AbstractByteBuf} implementation.
1370          * @param initialCapacity The initial capacity of the returned {@link AbstractByteBuf}.
1371          * @param maxCapacity The maximum capacity of the returned {@link AbstractByteBuf}.
1372          * @return The buffer that represents the chunk memory.
1373          */
1374         AbstractByteBuf allocate(int initialCapacity, int maxCapacity);
1375     }
1376 }