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