View Javadoc
1   /*
2    * Copyright 2012 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  
17  package io.netty.buffer;
18  
19  import static io.netty.util.internal.ObjectUtil.checkPositiveOrZero;
20  
21  import io.netty.util.NettyRuntime;
22  import io.netty.util.concurrent.EventExecutor;
23  import io.netty.util.concurrent.FastThreadLocal;
24  import io.netty.util.concurrent.FastThreadLocalThread;
25  import io.netty.util.internal.PlatformDependent;
26  import io.netty.util.internal.StringUtil;
27  import io.netty.util.internal.SystemPropertyUtil;
28  import io.netty.util.internal.ThreadExecutorMap;
29  import io.netty.util.internal.logging.InternalLogger;
30  import io.netty.util.internal.logging.InternalLoggerFactory;
31  
32  import java.nio.ByteBuffer;
33  import java.util.ArrayList;
34  import java.util.Collections;
35  import java.util.List;
36  import java.util.concurrent.TimeUnit;
37  
38  public class PooledByteBufAllocator extends AbstractByteBufAllocator implements ByteBufAllocatorMetricProvider {
39  
40      private static final InternalLogger logger = InternalLoggerFactory.getInstance(PooledByteBufAllocator.class);
41      private static final int DEFAULT_NUM_HEAP_ARENA;
42      private static final int DEFAULT_NUM_DIRECT_ARENA;
43  
44      private static final int DEFAULT_PAGE_SIZE;
45      private static final int DEFAULT_MAX_ORDER; // 8192 << 9 = 4 MiB per chunk
46      private static final int DEFAULT_SMALL_CACHE_SIZE;
47      private static final int DEFAULT_NORMAL_CACHE_SIZE;
48      static final int DEFAULT_MAX_CACHED_BUFFER_CAPACITY;
49      private static final int DEFAULT_CACHE_TRIM_INTERVAL;
50      private static final long DEFAULT_CACHE_TRIM_INTERVAL_MILLIS;
51      private static final boolean DEFAULT_USE_CACHE_FOR_ALL_THREADS;
52      private static final int DEFAULT_DIRECT_MEMORY_CACHE_ALIGNMENT;
53      static final int DEFAULT_MAX_CACHED_BYTEBUFFERS_PER_CHUNK;
54      private static final boolean DEFAULT_DISABLE_CACHE_FINALIZERS_FOR_FAST_THREAD_LOCAL_THREADS;
55  
56      private static final int MIN_PAGE_SIZE = 4096;
57      private static final int MAX_CHUNK_SIZE = (int) (((long) Integer.MAX_VALUE + 1) / 2);
58  
59      private static final int CACHE_NOT_USED = 0;
60  
61      private final Runnable trimTask = new Runnable() {
62          @Override
63          public void run() {
64              PooledByteBufAllocator.this.trimCurrentThreadCache();
65          }
66      };
67  
68      static {
69          int defaultAlignment = SystemPropertyUtil.getInt(
70                  "io.netty.allocator.directMemoryCacheAlignment", 0);
71          int defaultPageSize = SystemPropertyUtil.getInt("io.netty.allocator.pageSize", 8192);
72          Throwable pageSizeFallbackCause = null;
73          try {
74              validateAndCalculatePageShifts(defaultPageSize, defaultAlignment);
75          } catch (Throwable t) {
76              pageSizeFallbackCause = t;
77              defaultPageSize = 8192;
78              defaultAlignment = 0;
79          }
80          DEFAULT_PAGE_SIZE = defaultPageSize;
81          DEFAULT_DIRECT_MEMORY_CACHE_ALIGNMENT = defaultAlignment;
82  
83          int defaultMaxOrder = SystemPropertyUtil.getInt("io.netty.allocator.maxOrder", 9);
84          Throwable maxOrderFallbackCause = null;
85          try {
86              validateAndCalculateChunkSize(DEFAULT_PAGE_SIZE, defaultMaxOrder);
87          } catch (Throwable t) {
88              maxOrderFallbackCause = t;
89              defaultMaxOrder = 9;
90          }
91          DEFAULT_MAX_ORDER = defaultMaxOrder;
92  
93          // Determine reasonable default for nHeapArena and nDirectArena.
94          // Assuming each arena has 3 chunks, the pool should not consume more than 50% of max memory.
95          final Runtime runtime = Runtime.getRuntime();
96  
97          /*
98           * We use 2 * available processors by default to reduce contention as we use 2 * available processors for the
99           * number of EventLoops in NIO and EPOLL as well. If we choose a smaller number we will run into hot spots as
100          * allocation and de-allocation needs to be synchronized on the PoolArena.
101          *
102          * See https://github.com/netty/netty/issues/3888.
103          */
104         final int defaultMinNumArena = NettyRuntime.availableProcessors() * 2;
105         final int defaultChunkSize = DEFAULT_PAGE_SIZE << DEFAULT_MAX_ORDER;
106         DEFAULT_NUM_HEAP_ARENA = Math.max(0,
107                 SystemPropertyUtil.getInt(
108                         "io.netty.allocator.numHeapArenas",
109                         (int) Math.min(
110                                 defaultMinNumArena,
111                                 runtime.maxMemory() / defaultChunkSize / 2 / 3)));
112         DEFAULT_NUM_DIRECT_ARENA = Math.max(0,
113                 SystemPropertyUtil.getInt(
114                         "io.netty.allocator.numDirectArenas",
115                         (int) Math.min(
116                                 defaultMinNumArena,
117                                 PlatformDependent.maxDirectMemory() / defaultChunkSize / 2 / 3)));
118 
119         // cache sizes
120         DEFAULT_SMALL_CACHE_SIZE = SystemPropertyUtil.getInt("io.netty.allocator.smallCacheSize", 256);
121         DEFAULT_NORMAL_CACHE_SIZE = SystemPropertyUtil.getInt("io.netty.allocator.normalCacheSize", 64);
122 
123         // 32 kb is the default maximum capacity of the cached buffer. Similar to what is explained in
124         // 'Scalable memory allocation using jemalloc'
125         DEFAULT_MAX_CACHED_BUFFER_CAPACITY = SystemPropertyUtil.getInt(
126                 "io.netty.allocator.maxCachedBufferCapacity", 32 * 1024);
127 
128         // the number of threshold of allocations when cached entries will be freed up if not frequently used
129         DEFAULT_CACHE_TRIM_INTERVAL = SystemPropertyUtil.getInt(
130                 "io.netty.allocator.cacheTrimInterval", 8192);
131 
132         if (SystemPropertyUtil.contains("io.netty.allocation.cacheTrimIntervalMillis")) {
133             logger.warn("-Dio.netty.allocation.cacheTrimIntervalMillis is deprecated," +
134                     " use -Dio.netty.allocator.cacheTrimIntervalMillis");
135 
136             if (SystemPropertyUtil.contains("io.netty.allocator.cacheTrimIntervalMillis")) {
137                 // Both system properties are specified. Use the non-deprecated one.
138                 DEFAULT_CACHE_TRIM_INTERVAL_MILLIS = SystemPropertyUtil.getLong(
139                         "io.netty.allocator.cacheTrimIntervalMillis", 0);
140             } else {
141                 DEFAULT_CACHE_TRIM_INTERVAL_MILLIS = SystemPropertyUtil.getLong(
142                         "io.netty.allocation.cacheTrimIntervalMillis", 0);
143             }
144         } else {
145             DEFAULT_CACHE_TRIM_INTERVAL_MILLIS = SystemPropertyUtil.getLong(
146                     "io.netty.allocator.cacheTrimIntervalMillis", 0);
147         }
148 
149         DEFAULT_USE_CACHE_FOR_ALL_THREADS = SystemPropertyUtil.getBoolean(
150                 "io.netty.allocator.useCacheForAllThreads", false);
151 
152         DEFAULT_DISABLE_CACHE_FINALIZERS_FOR_FAST_THREAD_LOCAL_THREADS = SystemPropertyUtil.getBoolean(
153                 "io.netty.allocator.disableCacheFinalizersForFastThreadLocalThreads", false);
154 
155         // Use 1023 by default as we use an ArrayDeque as backing storage which will then allocate an internal array
156         // of 1024 elements. Otherwise we would allocate 2048 and only use 1024 which is wasteful.
157         DEFAULT_MAX_CACHED_BYTEBUFFERS_PER_CHUNK = SystemPropertyUtil.getInt(
158                 "io.netty.allocator.maxCachedByteBuffersPerChunk", 1023);
159 
160         if (logger.isDebugEnabled()) {
161             logger.debug("-Dio.netty.allocator.numHeapArenas: {}", DEFAULT_NUM_HEAP_ARENA);
162             logger.debug("-Dio.netty.allocator.numDirectArenas: {}", DEFAULT_NUM_DIRECT_ARENA);
163             if (pageSizeFallbackCause == null) {
164                 logger.debug("-Dio.netty.allocator.pageSize: {}", DEFAULT_PAGE_SIZE);
165             } else {
166                 logger.debug("-Dio.netty.allocator.pageSize: {}", DEFAULT_PAGE_SIZE, pageSizeFallbackCause);
167             }
168             if (maxOrderFallbackCause == null) {
169                 logger.debug("-Dio.netty.allocator.maxOrder: {}", DEFAULT_MAX_ORDER);
170             } else {
171                 logger.debug("-Dio.netty.allocator.maxOrder: {}", DEFAULT_MAX_ORDER, maxOrderFallbackCause);
172             }
173             logger.debug("-Dio.netty.allocator.chunkSize: {}", DEFAULT_PAGE_SIZE << DEFAULT_MAX_ORDER);
174             logger.debug("-Dio.netty.allocator.smallCacheSize: {}", DEFAULT_SMALL_CACHE_SIZE);
175             logger.debug("-Dio.netty.allocator.normalCacheSize: {}", DEFAULT_NORMAL_CACHE_SIZE);
176             logger.debug("-Dio.netty.allocator.maxCachedBufferCapacity: {}", DEFAULT_MAX_CACHED_BUFFER_CAPACITY);
177             logger.debug("-Dio.netty.allocator.cacheTrimInterval: {}", DEFAULT_CACHE_TRIM_INTERVAL);
178             logger.debug("-Dio.netty.allocator.cacheTrimIntervalMillis: {}", DEFAULT_CACHE_TRIM_INTERVAL_MILLIS);
179             logger.debug("-Dio.netty.allocator.useCacheForAllThreads: {}", DEFAULT_USE_CACHE_FOR_ALL_THREADS);
180             logger.debug("-Dio.netty.allocator.maxCachedByteBuffersPerChunk: {}",
181                     DEFAULT_MAX_CACHED_BYTEBUFFERS_PER_CHUNK);
182             logger.debug("-Dio.netty.allocator.disableCacheFinalizersForFastThreadLocalThreads: {}",
183                          DEFAULT_DISABLE_CACHE_FINALIZERS_FOR_FAST_THREAD_LOCAL_THREADS);
184         }
185     }
186 
187     public static final PooledByteBufAllocator DEFAULT =
188             new PooledByteBufAllocator(!PlatformDependent.isExplicitNoPreferDirect());
189 
190     private final PoolArena<byte[]>[] heapArenas;
191     private final PoolArena<ByteBuffer>[] directArenas;
192     private final int smallCacheSize;
193     private final int normalCacheSize;
194     private final List<PoolArenaMetric> heapArenaMetrics;
195     private final List<PoolArenaMetric> directArenaMetrics;
196     private final PoolThreadLocalCache threadCache;
197     private final int chunkSize;
198     private final PooledByteBufAllocatorMetric metric;
199 
200     public PooledByteBufAllocator() {
201         this(false);
202     }
203 
204     @SuppressWarnings("deprecation")
205     public PooledByteBufAllocator(boolean preferDirect) {
206         this(preferDirect, DEFAULT_NUM_HEAP_ARENA, DEFAULT_NUM_DIRECT_ARENA, DEFAULT_PAGE_SIZE, DEFAULT_MAX_ORDER);
207     }
208 
209     @SuppressWarnings("deprecation")
210     public PooledByteBufAllocator(int nHeapArena, int nDirectArena, int pageSize, int maxOrder) {
211         this(false, nHeapArena, nDirectArena, pageSize, maxOrder);
212     }
213 
214     /**
215      * @deprecated use
216      * {@link PooledByteBufAllocator#PooledByteBufAllocator(boolean, int, int, int, int, int, int, boolean)}
217      */
218     @Deprecated
219     public PooledByteBufAllocator(boolean preferDirect, int nHeapArena, int nDirectArena, int pageSize, int maxOrder) {
220         this(preferDirect, nHeapArena, nDirectArena, pageSize, maxOrder,
221              0, DEFAULT_SMALL_CACHE_SIZE, DEFAULT_NORMAL_CACHE_SIZE);
222     }
223 
224     /**
225      * @deprecated use
226      * {@link PooledByteBufAllocator#PooledByteBufAllocator(boolean, int, int, int, int, int, int, boolean)}
227      */
228     @Deprecated
229     public PooledByteBufAllocator(boolean preferDirect, int nHeapArena, int nDirectArena, int pageSize, int maxOrder,
230                                   int tinyCacheSize, int smallCacheSize, int normalCacheSize) {
231         this(preferDirect, nHeapArena, nDirectArena, pageSize, maxOrder, smallCacheSize,
232              normalCacheSize, DEFAULT_USE_CACHE_FOR_ALL_THREADS, DEFAULT_DIRECT_MEMORY_CACHE_ALIGNMENT);
233     }
234 
235     /**
236      * @deprecated use
237      * {@link PooledByteBufAllocator#PooledByteBufAllocator(boolean, int, int, int, int, int, int, boolean)}
238      */
239     @Deprecated
240     public PooledByteBufAllocator(boolean preferDirect, int nHeapArena,
241                                   int nDirectArena, int pageSize, int maxOrder, int tinyCacheSize,
242                                   int smallCacheSize, int normalCacheSize,
243                                   boolean useCacheForAllThreads) {
244         this(preferDirect, nHeapArena, nDirectArena, pageSize, maxOrder,
245              smallCacheSize, normalCacheSize,
246              useCacheForAllThreads);
247     }
248 
249     public PooledByteBufAllocator(boolean preferDirect, int nHeapArena,
250                                   int nDirectArena, int pageSize, int maxOrder,
251                                   int smallCacheSize, int normalCacheSize,
252                                   boolean useCacheForAllThreads) {
253         this(preferDirect, nHeapArena, nDirectArena, pageSize, maxOrder,
254              smallCacheSize, normalCacheSize,
255              useCacheForAllThreads, DEFAULT_DIRECT_MEMORY_CACHE_ALIGNMENT);
256     }
257 
258     /**
259      * @deprecated use
260      * {@link PooledByteBufAllocator#PooledByteBufAllocator(boolean, int, int, int, int, int, int, boolean, int)}
261      */
262     @Deprecated
263     public PooledByteBufAllocator(boolean preferDirect, int nHeapArena, int nDirectArena, int pageSize, int maxOrder,
264                                   int tinyCacheSize, int smallCacheSize, int normalCacheSize,
265                                   boolean useCacheForAllThreads, int directMemoryCacheAlignment) {
266         this(preferDirect, nHeapArena, nDirectArena, pageSize, maxOrder,
267              smallCacheSize, normalCacheSize,
268              useCacheForAllThreads, directMemoryCacheAlignment);
269     }
270 
271     public PooledByteBufAllocator(boolean preferDirect, int nHeapArena, int nDirectArena, int pageSize, int maxOrder,
272                                   int smallCacheSize, int normalCacheSize,
273                                   boolean useCacheForAllThreads, int directMemoryCacheAlignment) {
274         super(preferDirect);
275         threadCache = new PoolThreadLocalCache(useCacheForAllThreads);
276         this.smallCacheSize = smallCacheSize;
277         this.normalCacheSize = normalCacheSize;
278 
279         if (directMemoryCacheAlignment != 0) {
280             if (!PlatformDependent.hasAlignDirectByteBuffer()) {
281                 throw new UnsupportedOperationException("Buffer alignment is not supported. " +
282                         "Either Unsafe or ByteBuffer.alignSlice() must be available.");
283             }
284 
285             // Ensure page size is a whole multiple of the alignment, or bump it to the next whole multiple.
286             pageSize = (int) PlatformDependent.align(pageSize, directMemoryCacheAlignment);
287         }
288 
289         chunkSize = validateAndCalculateChunkSize(pageSize, maxOrder);
290 
291         checkPositiveOrZero(nHeapArena, "nHeapArena");
292         checkPositiveOrZero(nDirectArena, "nDirectArena");
293 
294         checkPositiveOrZero(directMemoryCacheAlignment, "directMemoryCacheAlignment");
295         if (directMemoryCacheAlignment > 0 && !isDirectMemoryCacheAlignmentSupported()) {
296             throw new IllegalArgumentException("directMemoryCacheAlignment is not supported");
297         }
298 
299         if ((directMemoryCacheAlignment & -directMemoryCacheAlignment) != directMemoryCacheAlignment) {
300             throw new IllegalArgumentException("directMemoryCacheAlignment: "
301                     + directMemoryCacheAlignment + " (expected: power of two)");
302         }
303 
304         int pageShifts = validateAndCalculatePageShifts(pageSize, directMemoryCacheAlignment);
305 
306         if (nHeapArena > 0) {
307             heapArenas = newArenaArray(nHeapArena);
308             List<PoolArenaMetric> metrics = new ArrayList<PoolArenaMetric>(heapArenas.length);
309             final SizeClasses sizeClasses = new SizeClasses(pageSize, pageShifts, chunkSize, 0);
310             for (int i = 0; i < heapArenas.length; i ++) {
311                 PoolArena.HeapArena arena = new PoolArena.HeapArena(this, sizeClasses);
312                 heapArenas[i] = arena;
313                 metrics.add(arena);
314             }
315             heapArenaMetrics = Collections.unmodifiableList(metrics);
316         } else {
317             heapArenas = null;
318             heapArenaMetrics = Collections.emptyList();
319         }
320 
321         if (nDirectArena > 0) {
322             directArenas = newArenaArray(nDirectArena);
323             List<PoolArenaMetric> metrics = new ArrayList<PoolArenaMetric>(directArenas.length);
324             final SizeClasses sizeClasses = new SizeClasses(pageSize, pageShifts, chunkSize,
325                     directMemoryCacheAlignment);
326             for (int i = 0; i < directArenas.length; i ++) {
327                 PoolArena.DirectArena arena = new PoolArena.DirectArena(this, sizeClasses);
328                 directArenas[i] = arena;
329                 metrics.add(arena);
330             }
331             directArenaMetrics = Collections.unmodifiableList(metrics);
332         } else {
333             directArenas = null;
334             directArenaMetrics = Collections.emptyList();
335         }
336         metric = new PooledByteBufAllocatorMetric(this);
337     }
338 
339     @SuppressWarnings("unchecked")
340     private static <T> PoolArena<T>[] newArenaArray(int size) {
341         return new PoolArena[size];
342     }
343 
344     private static int validateAndCalculatePageShifts(int pageSize, int alignment) {
345         if (pageSize < MIN_PAGE_SIZE) {
346             throw new IllegalArgumentException("pageSize: " + pageSize + " (expected: " + MIN_PAGE_SIZE + ')');
347         }
348 
349         if ((pageSize & pageSize - 1) != 0) {
350             throw new IllegalArgumentException("pageSize: " + pageSize + " (expected: power of 2)");
351         }
352 
353         if (pageSize < alignment) {
354             throw new IllegalArgumentException("Alignment cannot be greater than page size. " +
355                     "Alignment: " + alignment + ", page size: " + pageSize + '.');
356         }
357 
358         // Logarithm base 2. At this point we know that pageSize is a power of two.
359         return Integer.SIZE - 1 - Integer.numberOfLeadingZeros(pageSize);
360     }
361 
362     private static int validateAndCalculateChunkSize(int pageSize, int maxOrder) {
363         if (maxOrder > 14) {
364             throw new IllegalArgumentException("maxOrder: " + maxOrder + " (expected: 0-14)");
365         }
366 
367         // Ensure the resulting chunkSize does not overflow.
368         int chunkSize = pageSize;
369         for (int i = maxOrder; i > 0; i --) {
370             if (chunkSize > MAX_CHUNK_SIZE / 2) {
371                 throw new IllegalArgumentException(String.format(
372                         "pageSize (%d) << maxOrder (%d) must not exceed %d", pageSize, maxOrder, MAX_CHUNK_SIZE));
373             }
374             chunkSize <<= 1;
375         }
376         return chunkSize;
377     }
378 
379     @Override
380     protected ByteBuf newHeapBuffer(int initialCapacity, int maxCapacity) {
381         PoolThreadCache cache = threadCache.get();
382         PoolArena<byte[]> heapArena = cache.heapArena;
383 
384         final AbstractByteBuf buf;
385         if (heapArena != null) {
386             buf = heapArena.allocate(cache, initialCapacity, maxCapacity);
387         } else {
388             buf = PlatformDependent.hasUnsafe() ?
389                     new UnpooledUnsafeHeapByteBuf(this, initialCapacity, maxCapacity) :
390                     new UnpooledHeapByteBuf(this, initialCapacity, maxCapacity);
391             onAllocateBuffer(buf, false, false);
392         }
393         return toLeakAwareBuffer(buf);
394     }
395 
396     @Override
397     protected ByteBuf newDirectBuffer(int initialCapacity, int maxCapacity) {
398         PoolThreadCache cache = threadCache.get();
399         PoolArena<ByteBuffer> directArena = cache.directArena;
400 
401         final AbstractByteBuf buf;
402         if (directArena != null) {
403             buf = directArena.allocate(cache, initialCapacity, maxCapacity);
404         } else {
405             buf = UnsafeByteBufUtil.newDirectByteBuf(this, initialCapacity, maxCapacity);
406             onAllocateBuffer(buf, false, false);
407         }
408         return toLeakAwareBuffer(buf);
409     }
410 
411     /**
412      * Default number of heap arenas - System Property: io.netty.allocator.numHeapArenas - default 2 * cores
413      */
414     public static int defaultNumHeapArena() {
415         return DEFAULT_NUM_HEAP_ARENA;
416     }
417 
418     /**
419      * Default number of direct arenas - System Property: io.netty.allocator.numDirectArenas - default 2 * cores
420      */
421     public static int defaultNumDirectArena() {
422         return DEFAULT_NUM_DIRECT_ARENA;
423     }
424 
425     /**
426      * Default buffer page size - System Property: io.netty.allocator.pageSize - default 8192
427      */
428     public static int defaultPageSize() {
429         return DEFAULT_PAGE_SIZE;
430     }
431 
432     /**
433      * Default maximum order - System Property: io.netty.allocator.maxOrder - default 9
434      */
435     public static int defaultMaxOrder() {
436         return DEFAULT_MAX_ORDER;
437     }
438 
439     /**
440      * Default control creation of PoolThreadCache finalizers for FastThreadLocalThreads -
441      * System Property: io.netty.allocator.disableCacheFinalizersForFastThreadLocalThreads - default false
442      */
443     public static boolean defaultDisableCacheFinalizersForFastThreadLocalThreads() {
444         return DEFAULT_DISABLE_CACHE_FINALIZERS_FOR_FAST_THREAD_LOCAL_THREADS;
445     }
446 
447     /**
448      * Default thread caching behavior - System Property: io.netty.allocator.useCacheForAllThreads - default false
449      */
450     public static boolean defaultUseCacheForAllThreads() {
451         return DEFAULT_USE_CACHE_FOR_ALL_THREADS;
452     }
453 
454     /**
455      * Default prefer direct - System Property: io.netty.noPreferDirect - default false
456      */
457     public static boolean defaultPreferDirect() {
458         return PlatformDependent.directBufferPreferred();
459     }
460 
461     /**
462      * Default tiny cache size - default 0
463      *
464      * @deprecated Tiny caches have been merged into small caches.
465      */
466     @Deprecated
467     public static int defaultTinyCacheSize() {
468         return 0;
469     }
470 
471     /**
472      * Default small cache size - System Property: io.netty.allocator.smallCacheSize - default 256
473      */
474     public static int defaultSmallCacheSize() {
475         return DEFAULT_SMALL_CACHE_SIZE;
476     }
477 
478     /**
479      * Default normal cache size - System Property: io.netty.allocator.normalCacheSize - default 64
480      */
481     public static int defaultNormalCacheSize() {
482         return DEFAULT_NORMAL_CACHE_SIZE;
483     }
484 
485     /**
486      * Return {@code true} if direct memory cache alignment is supported, {@code false} otherwise.
487      */
488     public static boolean isDirectMemoryCacheAlignmentSupported() {
489         return PlatformDependent.hasUnsafe();
490     }
491 
492     @Override
493     public boolean isDirectBufferPooled() {
494         return directArenas != null;
495     }
496 
497     /**
498      * @deprecated will be removed
499      * Returns {@code true} if the calling {@link Thread} has a {@link ThreadLocal} cache for the allocated
500      * buffers.
501      */
502     @Deprecated
503     public boolean hasThreadLocalCache() {
504         return threadCache.isSet();
505     }
506 
507     /**
508      * @deprecated will be removed
509      * Free all cached buffers for the calling {@link Thread}.
510      */
511     @Deprecated
512     public void freeThreadLocalCache() {
513         threadCache.remove();
514     }
515 
516     private final class PoolThreadLocalCache extends FastThreadLocal<PoolThreadCache> {
517         private final boolean useCacheForAllThreads;
518 
519         PoolThreadLocalCache(boolean useCacheForAllThreads) {
520             this.useCacheForAllThreads = useCacheForAllThreads;
521         }
522 
523         @Override
524         protected synchronized PoolThreadCache initialValue() {
525             final PoolArena<byte[]> heapArena = leastUsedArena(heapArenas);
526             final PoolArena<ByteBuffer> directArena = leastUsedArena(directArenas);
527 
528             final Thread current = Thread.currentThread();
529             final EventExecutor executor = ThreadExecutorMap.currentExecutor();
530 
531             if (useCacheForAllThreads ||
532                     // If the current thread is a FastThreadLocalThread we will always use the cache
533                     FastThreadLocalThread.currentThreadHasFastThreadLocal() ||
534                     // The Thread is used by an EventExecutor, let's use the cache as the chances are good that we
535                     // will allocate a lot!
536                     executor != null) {
537                 final PoolThreadCache cache = new PoolThreadCache(
538                         heapArena, directArena, smallCacheSize, normalCacheSize,
539                         DEFAULT_MAX_CACHED_BUFFER_CAPACITY, DEFAULT_CACHE_TRIM_INTERVAL, useCacheFinalizers());
540 
541                 if (DEFAULT_CACHE_TRIM_INTERVAL_MILLIS > 0) {
542                     if (executor != null) {
543                         executor.scheduleAtFixedRate(trimTask, DEFAULT_CACHE_TRIM_INTERVAL_MILLIS,
544                                 DEFAULT_CACHE_TRIM_INTERVAL_MILLIS, TimeUnit.MILLISECONDS);
545                     }
546                 }
547                 return cache;
548             }
549             // No caching so just use 0 as sizes.
550             return new PoolThreadCache(heapArena, directArena, 0, 0, 0, 0, false);
551         }
552 
553         @Override
554         protected void onRemoval(PoolThreadCache threadCache) {
555             threadCache.free(false);
556         }
557 
558         private <T> PoolArena<T> leastUsedArena(PoolArena<T>[] arenas) {
559             if (arenas == null || arenas.length == 0) {
560                 return null;
561             }
562 
563             PoolArena<T> minArena = arenas[0];
564             //optimized
565             //If it is the first execution, directly return minarena and reduce the number of for loop comparisons below
566             if (minArena.numThreadCaches.get() == CACHE_NOT_USED) {
567                 return minArena;
568             }
569             for (int i = 1; i < arenas.length; i++) {
570                 PoolArena<T> arena = arenas[i];
571                 if (arena.numThreadCaches.get() < minArena.numThreadCaches.get()) {
572                     minArena = arena;
573                 }
574             }
575 
576             return minArena;
577         }
578     }
579 
580     private static boolean useCacheFinalizers() {
581         if (!defaultDisableCacheFinalizersForFastThreadLocalThreads()) {
582             return true;
583         }
584         return FastThreadLocalThread.currentThreadWillCleanupFastThreadLocals();
585     }
586 
587     @Override
588     public PooledByteBufAllocatorMetric metric() {
589         return metric;
590     }
591 
592     /**
593      * Return the number of heap arenas.
594      *
595      * @deprecated use {@link PooledByteBufAllocatorMetric#numHeapArenas()}.
596      */
597     @Deprecated
598     public int numHeapArenas() {
599         return heapArenaMetrics.size();
600     }
601 
602     /**
603      * Return the number of direct arenas.
604      *
605      * @deprecated use {@link PooledByteBufAllocatorMetric#numDirectArenas()}.
606      */
607     @Deprecated
608     public int numDirectArenas() {
609         return directArenaMetrics.size();
610     }
611 
612     /**
613      * Return a {@link List} of all heap {@link PoolArenaMetric}s that are provided by this pool.
614      *
615      * @deprecated use {@link PooledByteBufAllocatorMetric#heapArenas()}.
616      */
617     @Deprecated
618     public List<PoolArenaMetric> heapArenas() {
619         return heapArenaMetrics;
620     }
621 
622     /**
623      * Return a {@link List} of all direct {@link PoolArenaMetric}s that are provided by this pool.
624      *
625      * @deprecated use {@link PooledByteBufAllocatorMetric#directArenas()}.
626      */
627     @Deprecated
628     public List<PoolArenaMetric> directArenas() {
629         return directArenaMetrics;
630     }
631 
632     /**
633      * Return the number of thread local caches used by this {@link PooledByteBufAllocator}.
634      *
635      * @deprecated use {@link PooledByteBufAllocatorMetric#numThreadLocalCaches()}.
636      */
637     @Deprecated
638     public int numThreadLocalCaches() {
639         return Math.max(numThreadLocalCaches(heapArenas), numThreadLocalCaches(directArenas));
640     }
641 
642     private static int numThreadLocalCaches(PoolArena<?>[] arenas) {
643         if (arenas == null) {
644             return 0;
645         }
646 
647         int total = 0;
648         for (PoolArena<?> arena : arenas) {
649             total += arena.numThreadCaches.get();
650         }
651 
652         return total;
653     }
654 
655     /**
656      * Return the size of the tiny cache.
657      *
658      * @deprecated use {@link PooledByteBufAllocatorMetric#tinyCacheSize()}.
659      */
660     @Deprecated
661     public int tinyCacheSize() {
662         return 0;
663     }
664 
665     /**
666      * Return the size of the small cache.
667      *
668      * @deprecated use {@link PooledByteBufAllocatorMetric#smallCacheSize()}.
669      */
670     @Deprecated
671     public int smallCacheSize() {
672         return smallCacheSize;
673     }
674 
675     /**
676      * Return the size of the normal cache.
677      *
678      * @deprecated use {@link PooledByteBufAllocatorMetric#normalCacheSize()}.
679      */
680     @Deprecated
681     public int normalCacheSize() {
682         return normalCacheSize;
683     }
684 
685     /**
686      * Return the chunk size for an arena.
687      *
688      * @deprecated use {@link PooledByteBufAllocatorMetric#chunkSize()}.
689      */
690     @Deprecated
691     public final int chunkSize() {
692         return chunkSize;
693     }
694 
695     final long usedHeapMemory() {
696         return usedMemory(heapArenas);
697     }
698 
699     final long usedDirectMemory() {
700         return usedMemory(directArenas);
701     }
702 
703     private static long usedMemory(PoolArena<?>[] arenas) {
704         if (arenas == null) {
705             return -1;
706         }
707         long used = 0;
708         for (PoolArena<?> arena : arenas) {
709             used += arena.numActiveBytes();
710             if (used < 0) {
711                 return Long.MAX_VALUE;
712             }
713         }
714         return used;
715     }
716 
717     /**
718      * Returns the number of bytes of heap memory that is currently pinned to heap buffers allocated by a
719      * {@link ByteBufAllocator}, or {@code -1} if unknown.
720      * A buffer can pin more memory than its {@linkplain ByteBuf#capacity() capacity} might indicate,
721      * due to implementation details of the allocator.
722      */
723     public final long pinnedHeapMemory() {
724         return pinnedMemory(heapArenas);
725     }
726 
727     /**
728      * Returns the number of bytes of direct memory that is currently pinned to direct buffers allocated by a
729      * {@link ByteBufAllocator}, or {@code -1} if unknown.
730      * A buffer can pin more memory than its {@linkplain ByteBuf#capacity() capacity} might indicate,
731      * due to implementation details of the allocator.
732      */
733     public final long pinnedDirectMemory() {
734         return pinnedMemory(directArenas);
735     }
736 
737     private static long pinnedMemory(PoolArena<?>[] arenas) {
738         if (arenas == null) {
739             return -1;
740         }
741         long used = 0;
742         for (PoolArena<?> arena : arenas) {
743             used += arena.numPinnedBytes();
744             if (used < 0) {
745                 return Long.MAX_VALUE;
746             }
747         }
748         return used;
749     }
750 
751     final PoolThreadCache threadCache() {
752         PoolThreadCache cache =  threadCache.get();
753         assert cache != null;
754         return cache;
755     }
756 
757     /**
758      * Trim thread local cache for the current {@link Thread}, which will give back any cached memory that was not
759      * allocated frequently since the last trim operation.
760      *
761      * Returns {@code true} if a cache for the current {@link Thread} exists and so was trimmed, false otherwise.
762      */
763     public boolean trimCurrentThreadCache() {
764         PoolThreadCache cache = threadCache.getIfExists();
765         if (cache != null) {
766             cache.trim();
767             return true;
768         }
769         return false;
770     }
771 
772     /**
773      * Returns the status of the allocator (which contains all metrics) as string. Be aware this may be expensive
774      * and so should not called too frequently.
775      */
776     public String dumpStats() {
777         int heapArenasLen = heapArenas == null ? 0 : heapArenas.length;
778         StringBuilder buf = new StringBuilder(512)
779                 .append(heapArenasLen)
780                 .append(" heap arena(s):")
781                 .append(StringUtil.NEWLINE);
782         if (heapArenasLen > 0) {
783             for (PoolArena<byte[]> a: heapArenas) {
784                 buf.append(a);
785             }
786         }
787 
788         int directArenasLen = directArenas == null ? 0 : directArenas.length;
789 
790         buf.append(directArenasLen)
791            .append(" direct arena(s):")
792            .append(StringUtil.NEWLINE);
793         if (directArenasLen > 0) {
794             for (PoolArena<ByteBuffer> a: directArenas) {
795                 buf.append(a);
796             }
797         }
798 
799         return buf.toString();
800     }
801 
802     static void onAllocateBuffer(AbstractByteBuf buf, boolean pooled, boolean threadLocal) {
803         if (PlatformDependent.isJfrEnabled() && AllocateBufferEvent.isEventEnabled()) {
804             AllocateBufferEvent event = new AllocateBufferEvent();
805             if (event.shouldCommit()) {
806                 event.fill(buf, PooledByteBufAllocator.class);
807                 event.chunkPooled = pooled;
808                 event.chunkThreadLocal = threadLocal;
809                 event.commit();
810             }
811         }
812     }
813 
814     static void onDeallocateBuffer(AbstractByteBuf buf) {
815         if (PlatformDependent.isJfrEnabled() && FreeBufferEvent.isEventEnabled()) {
816             FreeBufferEvent event = new FreeBufferEvent();
817             if (event.shouldCommit()) {
818                 event.fill(buf, PooledByteBufAllocator.class);
819                 event.commit();
820             }
821         }
822     }
823 
824     static void onReallocateBuffer(AbstractByteBuf buf, int newCapacity) {
825         if (PlatformDependent.isJfrEnabled() && ReallocateBufferEvent.isEventEnabled()) {
826             ReallocateBufferEvent event = new ReallocateBufferEvent();
827             if (event.shouldCommit()) {
828                 event.fill(buf, PooledByteBufAllocator.class);
829                 event.newCapacity = newCapacity;
830                 event.commit();
831             }
832         }
833     }
834 
835     static void onAllocateChunk(ChunkInfo chunk, boolean pooled) {
836         if (PlatformDependent.isJfrEnabled() && AllocateChunkEvent.isEventEnabled()) {
837             AllocateChunkEvent event = new AllocateChunkEvent();
838             if (event.shouldCommit()) {
839                 event.fill(chunk, PooledByteBufAllocator.class);
840                 event.pooled = pooled;
841                 event.threadLocal = false; // Chunks in the pooled allocator are always shared.
842                 event.commit();
843             }
844         }
845     }
846 
847     static void onDeallocateChunk(ChunkInfo chunk, boolean pooled) {
848         if (PlatformDependent.isJfrEnabled() && FreeChunkEvent.isEventEnabled()) {
849             FreeChunkEvent event = new FreeChunkEvent();
850             if (event.shouldCommit()) {
851                 event.fill(chunk, PooledByteBufAllocator.class);
852                 event.pooled = pooled;
853                 event.commit();
854             }
855         }
856     }
857 }