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    *   http://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 io.netty.util.NettyRuntime;
20  import io.netty.util.concurrent.FastThreadLocal;
21  import io.netty.util.concurrent.FastThreadLocalThread;
22  import io.netty.util.internal.PlatformDependent;
23  import io.netty.util.internal.StringUtil;
24  import io.netty.util.internal.SystemPropertyUtil;
25  import io.netty.util.internal.logging.InternalLogger;
26  import io.netty.util.internal.logging.InternalLoggerFactory;
27  
28  import java.nio.ByteBuffer;
29  import java.util.ArrayList;
30  import java.util.Collections;
31  import java.util.List;
32  
33  public class PooledByteBufAllocator extends AbstractByteBufAllocator implements ByteBufAllocatorMetricProvider {
34  
35      private static final InternalLogger logger = InternalLoggerFactory.getInstance(PooledByteBufAllocator.class);
36      private static final int DEFAULT_NUM_HEAP_ARENA;
37      private static final int DEFAULT_NUM_DIRECT_ARENA;
38  
39      private static final int DEFAULT_PAGE_SIZE;
40      private static final int DEFAULT_MAX_ORDER; // 8192 << 11 = 16 MiB per chunk
41      private static final int DEFAULT_TINY_CACHE_SIZE;
42      private static final int DEFAULT_SMALL_CACHE_SIZE;
43      private static final int DEFAULT_NORMAL_CACHE_SIZE;
44      private static final int DEFAULT_MAX_CACHED_BUFFER_CAPACITY;
45      private static final int DEFAULT_CACHE_TRIM_INTERVAL;
46      private static final boolean DEFAULT_USE_CACHE_FOR_ALL_THREADS;
47      private static final int DEFAULT_DIRECT_MEMORY_CACHE_ALIGNMENT;
48  
49      private static final int MIN_PAGE_SIZE = 4096;
50      private static final int MAX_CHUNK_SIZE = (int) (((long) Integer.MAX_VALUE + 1) / 2);
51  
52      static {
53          int defaultPageSize = SystemPropertyUtil.getInt("io.netty.allocator.pageSize", 8192);
54          Throwable pageSizeFallbackCause = null;
55          try {
56              validateAndCalculatePageShifts(defaultPageSize);
57          } catch (Throwable t) {
58              pageSizeFallbackCause = t;
59              defaultPageSize = 8192;
60          }
61          DEFAULT_PAGE_SIZE = defaultPageSize;
62  
63          int defaultMaxOrder = SystemPropertyUtil.getInt("io.netty.allocator.maxOrder", 11);
64          Throwable maxOrderFallbackCause = null;
65          try {
66              validateAndCalculateChunkSize(DEFAULT_PAGE_SIZE, defaultMaxOrder);
67          } catch (Throwable t) {
68              maxOrderFallbackCause = t;
69              defaultMaxOrder = 11;
70          }
71          DEFAULT_MAX_ORDER = defaultMaxOrder;
72  
73          // Determine reasonable default for nHeapArena and nDirectArena.
74          // Assuming each arena has 3 chunks, the pool should not consume more than 50% of max memory.
75          final Runtime runtime = Runtime.getRuntime();
76  
77          /*
78           * We use 2 * available processors by default to reduce contention as we use 2 * available processors for the
79           * number of EventLoops in NIO and EPOLL as well. If we choose a smaller number we will run into hot spots as
80           * allocation and de-allocation needs to be synchronized on the PoolArena.
81           *
82           * See https://github.com/netty/netty/issues/3888.
83           */
84          final int defaultMinNumArena = NettyRuntime.availableProcessors() * 2;
85          final int defaultChunkSize = DEFAULT_PAGE_SIZE << DEFAULT_MAX_ORDER;
86          DEFAULT_NUM_HEAP_ARENA = Math.max(0,
87                  SystemPropertyUtil.getInt(
88                          "io.netty.allocator.numHeapArenas",
89                          (int) Math.min(
90                                  defaultMinNumArena,
91                                  runtime.maxMemory() / defaultChunkSize / 2 / 3)));
92          DEFAULT_NUM_DIRECT_ARENA = Math.max(0,
93                  SystemPropertyUtil.getInt(
94                          "io.netty.allocator.numDirectArenas",
95                          (int) Math.min(
96                                  defaultMinNumArena,
97                                  PlatformDependent.maxDirectMemory() / defaultChunkSize / 2 / 3)));
98  
99          // cache sizes
100         DEFAULT_TINY_CACHE_SIZE = SystemPropertyUtil.getInt("io.netty.allocator.tinyCacheSize", 512);
101         DEFAULT_SMALL_CACHE_SIZE = SystemPropertyUtil.getInt("io.netty.allocator.smallCacheSize", 256);
102         DEFAULT_NORMAL_CACHE_SIZE = SystemPropertyUtil.getInt("io.netty.allocator.normalCacheSize", 64);
103 
104         // 32 kb is the default maximum capacity of the cached buffer. Similar to what is explained in
105         // 'Scalable memory allocation using jemalloc'
106         DEFAULT_MAX_CACHED_BUFFER_CAPACITY = SystemPropertyUtil.getInt(
107                 "io.netty.allocator.maxCachedBufferCapacity", 32 * 1024);
108 
109         // the number of threshold of allocations when cached entries will be freed up if not frequently used
110         DEFAULT_CACHE_TRIM_INTERVAL = SystemPropertyUtil.getInt(
111                 "io.netty.allocator.cacheTrimInterval", 8192);
112 
113         DEFAULT_USE_CACHE_FOR_ALL_THREADS = SystemPropertyUtil.getBoolean(
114                 "io.netty.allocator.useCacheForAllThreads", true);
115 
116         DEFAULT_DIRECT_MEMORY_CACHE_ALIGNMENT = SystemPropertyUtil.getInt(
117                 "io.netty.allocator.directMemoryCacheAlignment", 0);
118 
119         if (logger.isDebugEnabled()) {
120             logger.debug("-Dio.netty.allocator.numHeapArenas: {}", DEFAULT_NUM_HEAP_ARENA);
121             logger.debug("-Dio.netty.allocator.numDirectArenas: {}", DEFAULT_NUM_DIRECT_ARENA);
122             if (pageSizeFallbackCause == null) {
123                 logger.debug("-Dio.netty.allocator.pageSize: {}", DEFAULT_PAGE_SIZE);
124             } else {
125                 logger.debug("-Dio.netty.allocator.pageSize: {}", DEFAULT_PAGE_SIZE, pageSizeFallbackCause);
126             }
127             if (maxOrderFallbackCause == null) {
128                 logger.debug("-Dio.netty.allocator.maxOrder: {}", DEFAULT_MAX_ORDER);
129             } else {
130                 logger.debug("-Dio.netty.allocator.maxOrder: {}", DEFAULT_MAX_ORDER, maxOrderFallbackCause);
131             }
132             logger.debug("-Dio.netty.allocator.chunkSize: {}", DEFAULT_PAGE_SIZE << DEFAULT_MAX_ORDER);
133             logger.debug("-Dio.netty.allocator.tinyCacheSize: {}", DEFAULT_TINY_CACHE_SIZE);
134             logger.debug("-Dio.netty.allocator.smallCacheSize: {}", DEFAULT_SMALL_CACHE_SIZE);
135             logger.debug("-Dio.netty.allocator.normalCacheSize: {}", DEFAULT_NORMAL_CACHE_SIZE);
136             logger.debug("-Dio.netty.allocator.maxCachedBufferCapacity: {}", DEFAULT_MAX_CACHED_BUFFER_CAPACITY);
137             logger.debug("-Dio.netty.allocator.cacheTrimInterval: {}", DEFAULT_CACHE_TRIM_INTERVAL);
138             logger.debug("-Dio.netty.allocator.useCacheForAllThreads: {}", DEFAULT_USE_CACHE_FOR_ALL_THREADS);
139         }
140     }
141 
142     public static final PooledByteBufAllocator DEFAULT =
143             new PooledByteBufAllocator(PlatformDependent.directBufferPreferred());
144 
145     private final PoolArena<byte[]>[] heapArenas;
146     private final PoolArena<ByteBuffer>[] directArenas;
147     private final int tinyCacheSize;
148     private final int smallCacheSize;
149     private final int normalCacheSize;
150     private final List<PoolArenaMetric> heapArenaMetrics;
151     private final List<PoolArenaMetric> directArenaMetrics;
152     private final PoolThreadLocalCache threadCache;
153     private final int chunkSize;
154     private final PooledByteBufAllocatorMetric metric;
155 
156     public PooledByteBufAllocator() {
157         this(false);
158     }
159 
160     @SuppressWarnings("deprecation")
161     public PooledByteBufAllocator(boolean preferDirect) {
162         this(preferDirect, DEFAULT_NUM_HEAP_ARENA, DEFAULT_NUM_DIRECT_ARENA, DEFAULT_PAGE_SIZE, DEFAULT_MAX_ORDER);
163     }
164 
165     @SuppressWarnings("deprecation")
166     public PooledByteBufAllocator(int nHeapArena, int nDirectArena, int pageSize, int maxOrder) {
167         this(false, nHeapArena, nDirectArena, pageSize, maxOrder);
168     }
169 
170     /**
171      * @deprecated use
172      * {@link PooledByteBufAllocator#PooledByteBufAllocator(boolean, int, int, int, int, int, int, int, boolean)}
173      */
174     @Deprecated
175     public PooledByteBufAllocator(boolean preferDirect, int nHeapArena, int nDirectArena, int pageSize, int maxOrder) {
176         this(preferDirect, nHeapArena, nDirectArena, pageSize, maxOrder,
177                 DEFAULT_TINY_CACHE_SIZE, DEFAULT_SMALL_CACHE_SIZE, DEFAULT_NORMAL_CACHE_SIZE);
178     }
179 
180     /**
181      * @deprecated use
182      * {@link PooledByteBufAllocator#PooledByteBufAllocator(boolean, int, int, int, int, int, int, int, boolean)}
183      */
184     @Deprecated
185     public PooledByteBufAllocator(boolean preferDirect, int nHeapArena, int nDirectArena, int pageSize, int maxOrder,
186                                   int tinyCacheSize, int smallCacheSize, int normalCacheSize) {
187         this(preferDirect, nHeapArena, nDirectArena, pageSize, maxOrder, tinyCacheSize, smallCacheSize,
188                 normalCacheSize, DEFAULT_USE_CACHE_FOR_ALL_THREADS, DEFAULT_DIRECT_MEMORY_CACHE_ALIGNMENT);
189     }
190 
191     public PooledByteBufAllocator(boolean preferDirect, int nHeapArena,
192                                   int nDirectArena, int pageSize, int maxOrder, int tinyCacheSize,
193                                   int smallCacheSize, int normalCacheSize,
194                                   boolean useCacheForAllThreads) {
195         this(preferDirect, nHeapArena, nDirectArena, pageSize, maxOrder,
196                 tinyCacheSize, smallCacheSize, normalCacheSize,
197                 useCacheForAllThreads, DEFAULT_DIRECT_MEMORY_CACHE_ALIGNMENT);
198     }
199 
200     public PooledByteBufAllocator(boolean preferDirect, int nHeapArena, int nDirectArena, int pageSize, int maxOrder,
201                                   int tinyCacheSize, int smallCacheSize, int normalCacheSize,
202                                   boolean useCacheForAllThreads, int directMemoryCacheAlignment) {
203         super(preferDirect);
204         threadCache = new PoolThreadLocalCache(useCacheForAllThreads);
205         this.tinyCacheSize = tinyCacheSize;
206         this.smallCacheSize = smallCacheSize;
207         this.normalCacheSize = normalCacheSize;
208         chunkSize = validateAndCalculateChunkSize(pageSize, maxOrder);
209 
210         if (nHeapArena < 0) {
211             throw new IllegalArgumentException("nHeapArena: " + nHeapArena + " (expected: >= 0)");
212         }
213         if (nDirectArena < 0) {
214             throw new IllegalArgumentException("nDirectArea: " + nDirectArena + " (expected: >= 0)");
215         }
216 
217         if (directMemoryCacheAlignment < 0) {
218             throw new IllegalArgumentException("directMemoryCacheAlignment: "
219                     + directMemoryCacheAlignment + " (expected: >= 0)");
220         }
221         if (directMemoryCacheAlignment > 0 && !isDirectMemoryCacheAlignmentSupported()) {
222             throw new IllegalArgumentException("directMemoryCacheAlignment is not supported");
223         }
224 
225         if ((directMemoryCacheAlignment & -directMemoryCacheAlignment) != directMemoryCacheAlignment) {
226             throw new IllegalArgumentException("directMemoryCacheAlignment: "
227                     + directMemoryCacheAlignment + " (expected: power of two)");
228         }
229 
230         int pageShifts = validateAndCalculatePageShifts(pageSize);
231 
232         if (nHeapArena > 0) {
233             heapArenas = newArenaArray(nHeapArena);
234             List<PoolArenaMetric> metrics = new ArrayList<PoolArenaMetric>(heapArenas.length);
235             for (int i = 0; i < heapArenas.length; i ++) {
236                 PoolArena.HeapArena arena = new PoolArena.HeapArena(this,
237                         pageSize, maxOrder, pageShifts, chunkSize,
238                         directMemoryCacheAlignment);
239                 heapArenas[i] = arena;
240                 metrics.add(arena);
241             }
242             heapArenaMetrics = Collections.unmodifiableList(metrics);
243         } else {
244             heapArenas = null;
245             heapArenaMetrics = Collections.emptyList();
246         }
247 
248         if (nDirectArena > 0) {
249             directArenas = newArenaArray(nDirectArena);
250             List<PoolArenaMetric> metrics = new ArrayList<PoolArenaMetric>(directArenas.length);
251             for (int i = 0; i < directArenas.length; i ++) {
252                 PoolArena.DirectArena arena = new PoolArena.DirectArena(
253                         this, pageSize, maxOrder, pageShifts, chunkSize, directMemoryCacheAlignment);
254                 directArenas[i] = arena;
255                 metrics.add(arena);
256             }
257             directArenaMetrics = Collections.unmodifiableList(metrics);
258         } else {
259             directArenas = null;
260             directArenaMetrics = Collections.emptyList();
261         }
262         metric = new PooledByteBufAllocatorMetric(this);
263     }
264 
265     @SuppressWarnings("unchecked")
266     private static <T> PoolArena<T>[] newArenaArray(int size) {
267         return new PoolArena[size];
268     }
269 
270     private static int validateAndCalculatePageShifts(int pageSize) {
271         if (pageSize < MIN_PAGE_SIZE) {
272             throw new IllegalArgumentException("pageSize: " + pageSize + " (expected: " + MIN_PAGE_SIZE + ")");
273         }
274 
275         if ((pageSize & pageSize - 1) != 0) {
276             throw new IllegalArgumentException("pageSize: " + pageSize + " (expected: power of 2)");
277         }
278 
279         // Logarithm base 2. At this point we know that pageSize is a power of two.
280         return Integer.SIZE - 1 - Integer.numberOfLeadingZeros(pageSize);
281     }
282 
283     private static int validateAndCalculateChunkSize(int pageSize, int maxOrder) {
284         if (maxOrder > 14) {
285             throw new IllegalArgumentException("maxOrder: " + maxOrder + " (expected: 0-14)");
286         }
287 
288         // Ensure the resulting chunkSize does not overflow.
289         int chunkSize = pageSize;
290         for (int i = maxOrder; i > 0; i --) {
291             if (chunkSize > MAX_CHUNK_SIZE / 2) {
292                 throw new IllegalArgumentException(String.format(
293                         "pageSize (%d) << maxOrder (%d) must not exceed %d", pageSize, maxOrder, MAX_CHUNK_SIZE));
294             }
295             chunkSize <<= 1;
296         }
297         return chunkSize;
298     }
299 
300     @Override
301     protected ByteBuf newHeapBuffer(int initialCapacity, int maxCapacity) {
302         PoolThreadCache cache = threadCache.get();
303         PoolArena<byte[]> heapArena = cache.heapArena;
304 
305         final ByteBuf buf;
306         if (heapArena != null) {
307             buf = heapArena.allocate(cache, initialCapacity, maxCapacity);
308         } else {
309             buf = PlatformDependent.hasUnsafe() ?
310                     new UnpooledUnsafeHeapByteBuf(this, initialCapacity, maxCapacity) :
311                     new UnpooledHeapByteBuf(this, initialCapacity, maxCapacity);
312         }
313 
314         return toLeakAwareBuffer(buf);
315     }
316 
317     @Override
318     protected ByteBuf newDirectBuffer(int initialCapacity, int maxCapacity) {
319         PoolThreadCache cache = threadCache.get();
320         PoolArena<ByteBuffer> directArena = cache.directArena;
321 
322         final ByteBuf buf;
323         if (directArena != null) {
324             buf = directArena.allocate(cache, initialCapacity, maxCapacity);
325         } else {
326             buf = PlatformDependent.hasUnsafe() ?
327                     UnsafeByteBufUtil.newUnsafeDirectByteBuf(this, initialCapacity, maxCapacity) :
328                     new UnpooledDirectByteBuf(this, initialCapacity, maxCapacity);
329         }
330 
331         return toLeakAwareBuffer(buf);
332     }
333 
334     /**
335      * Default number of heap arenas - System Property: io.netty.allocator.numHeapArenas - default 2 * cores
336      */
337     public static int defaultNumHeapArena() {
338         return DEFAULT_NUM_HEAP_ARENA;
339     }
340 
341     /**
342      * Default number of direct arenas - System Property: io.netty.allocator.numDirectArenas - default 2 * cores
343      */
344     public static int defaultNumDirectArena() {
345         return DEFAULT_NUM_DIRECT_ARENA;
346     }
347 
348     /**
349      * Default buffer page size - System Property: io.netty.allocator.pageSize - default 8192
350      */
351     public static int defaultPageSize() {
352         return DEFAULT_PAGE_SIZE;
353     }
354 
355     /**
356      * Default maximum order - System Property: io.netty.allocator.maxOrder - default 11
357      */
358     public static int defaultMaxOrder() {
359         return DEFAULT_MAX_ORDER;
360     }
361 
362     /**
363      * Default thread caching behavior - System Property: io.netty.allocator.useCacheForAllThreads - default true
364      */
365     public static boolean defaultUseCacheForAllThreads() {
366         return DEFAULT_USE_CACHE_FOR_ALL_THREADS;
367     }
368 
369     /**
370      * Default prefer direct - System Property: io.netty.noPreferDirect - default false
371      */
372     public static boolean defaultPreferDirect() {
373         return PlatformDependent.directBufferPreferred();
374     }
375 
376     /**
377      * Default tiny cache size - System Property: io.netty.allocator.tinyCacheSize - default 512
378      */
379     public static int defaultTinyCacheSize() {
380         return DEFAULT_TINY_CACHE_SIZE;
381     }
382 
383     /**
384      * Default small cache size - System Property: io.netty.allocator.smallCacheSize - default 256
385      */
386     public static int defaultSmallCacheSize() {
387         return DEFAULT_SMALL_CACHE_SIZE;
388     }
389 
390     /**
391      * Default normal cache size - System Property: io.netty.allocator.normalCacheSize - default 64
392      */
393     public static int defaultNormalCacheSize() {
394         return DEFAULT_NORMAL_CACHE_SIZE;
395     }
396 
397     /**
398      * Return {@code true} if direct memory cache alignment is supported, {@code false} otherwise.
399      */
400     public static boolean isDirectMemoryCacheAlignmentSupported() {
401         return PlatformDependent.hasUnsafe();
402     }
403 
404     @Override
405     public boolean isDirectBufferPooled() {
406         return directArenas != null;
407     }
408 
409     /**
410      * Returns {@code true} if the calling {@link Thread} has a {@link ThreadLocal} cache for the allocated
411      * buffers.
412      */
413     @Deprecated
414     public boolean hasThreadLocalCache() {
415         return threadCache.isSet();
416     }
417 
418     /**
419      * Free all cached buffers for the calling {@link Thread}.
420      */
421     @Deprecated
422     public void freeThreadLocalCache() {
423         threadCache.remove();
424     }
425 
426     final class PoolThreadLocalCache extends FastThreadLocal<PoolThreadCache> {
427         private final boolean useCacheForAllThreads;
428 
429         PoolThreadLocalCache(boolean useCacheForAllThreads) {
430             this.useCacheForAllThreads = useCacheForAllThreads;
431         }
432 
433         @Override
434         protected synchronized PoolThreadCache initialValue() {
435             final PoolArena<byte[]> heapArena = leastUsedArena(heapArenas);
436             final PoolArena<ByteBuffer> directArena = leastUsedArena(directArenas);
437 
438             Thread current = Thread.currentThread();
439             boolean fastThread = current instanceof FastThreadLocalThread;
440             if (useCacheForAllThreads || current instanceof FastThreadLocalThread) {
441                 // If our FastThreadLocalThread will call FastThreadLocal.removeAll() we not need to use
442                 // the ThreadDeathWatcher to release memory from the PoolThreadCache once the Thread dies.
443                 boolean useTheadWatcher = fastThread ?
444                         !((FastThreadLocalThread) current).willCleanupFastThreadLocals() : true;
445                 return new PoolThreadCache(
446                         heapArena, directArena, tinyCacheSize, smallCacheSize, normalCacheSize,
447                         DEFAULT_MAX_CACHED_BUFFER_CAPACITY, DEFAULT_CACHE_TRIM_INTERVAL, useTheadWatcher);
448             }
449             // No caching for non FastThreadLocalThreads.
450             return new PoolThreadCache(heapArena, directArena, 0, 0, 0, 0, 0, false);
451         }
452 
453         @Override
454         protected void onRemoval(PoolThreadCache threadCache) {
455             threadCache.free();
456         }
457 
458         private <T> PoolArena<T> leastUsedArena(PoolArena<T>[] arenas) {
459             if (arenas == null || arenas.length == 0) {
460                 return null;
461             }
462 
463             PoolArena<T> minArena = arenas[0];
464             for (int i = 1; i < arenas.length; i++) {
465                 PoolArena<T> arena = arenas[i];
466                 if (arena.numThreadCaches.get() < minArena.numThreadCaches.get()) {
467                     minArena = arena;
468                 }
469             }
470 
471             return minArena;
472         }
473     }
474 
475     @Override
476     public PooledByteBufAllocatorMetric metric() {
477         return metric;
478     }
479 
480     /**
481      * Return the number of heap arenas.
482      *
483      * @deprecated use {@link PooledByteBufAllocatorMetric#numHeapArenas()}.
484      */
485     @Deprecated
486     public int numHeapArenas() {
487         return heapArenaMetrics.size();
488     }
489 
490     /**
491      * Return the number of direct arenas.
492      *
493      * @deprecated use {@link PooledByteBufAllocatorMetric#numDirectArenas()}.
494      */
495     @Deprecated
496     public int numDirectArenas() {
497         return directArenaMetrics.size();
498     }
499 
500     /**
501      * Return a {@link List} of all heap {@link PoolArenaMetric}s that are provided by this pool.
502      *
503      * @deprecated use {@link PooledByteBufAllocatorMetric#heapArenas()}.
504      */
505     @Deprecated
506     public List<PoolArenaMetric> heapArenas() {
507         return heapArenaMetrics;
508     }
509 
510     /**
511      * Return a {@link List} of all direct {@link PoolArenaMetric}s that are provided by this pool.
512      *
513      * @deprecated use {@link PooledByteBufAllocatorMetric#directArenas()}.
514      */
515     @Deprecated
516     public List<PoolArenaMetric> directArenas() {
517         return directArenaMetrics;
518     }
519 
520     /**
521      * Return the number of thread local caches used by this {@link PooledByteBufAllocator}.
522      *
523      * @deprecated use {@link PooledByteBufAllocatorMetric#numThreadLocalCaches()}.
524      */
525     @Deprecated
526     public int numThreadLocalCaches() {
527         PoolArena<?>[] arenas = heapArenas != null ? heapArenas : directArenas;
528         if (arenas == null) {
529             return 0;
530         }
531 
532         int total = 0;
533         for (PoolArena<?> arena : arenas) {
534             total += arena.numThreadCaches.get();
535         }
536 
537         return total;
538     }
539 
540     /**
541      * Return the size of the tiny cache.
542      *
543      * @deprecated use {@link PooledByteBufAllocatorMetric#tinyCacheSize()}.
544      */
545     @Deprecated
546     public int tinyCacheSize() {
547         return tinyCacheSize;
548     }
549 
550     /**
551      * Return the size of the small cache.
552      *
553      * @deprecated use {@link PooledByteBufAllocatorMetric#smallCacheSize()}.
554      */
555     @Deprecated
556     public int smallCacheSize() {
557         return smallCacheSize;
558     }
559 
560     /**
561      * Return the size of the normal cache.
562      *
563      * @deprecated use {@link PooledByteBufAllocatorMetric#normalCacheSize()}.
564      */
565     @Deprecated
566     public int normalCacheSize() {
567         return normalCacheSize;
568     }
569 
570     /**
571      * Return the chunk size for an arena.
572      *
573      * @deprecated use {@link PooledByteBufAllocatorMetric#chunkSize()}.
574      */
575     @Deprecated
576     public final int chunkSize() {
577         return chunkSize;
578     }
579 
580     final long usedHeapMemory() {
581         return usedMemory(heapArenas);
582     }
583 
584     final long usedDirectMemory() {
585         return usedMemory(directArenas);
586     }
587 
588     private static long usedMemory(PoolArena<?>... arenas) {
589         if (arenas == null) {
590             return -1;
591         }
592         long used = 0;
593         for (PoolArena<?> arena : arenas) {
594             used += arena.numActiveBytes();
595             if (used < 0) {
596                 return Long.MAX_VALUE;
597             }
598         }
599         return used;
600     }
601 
602     final PoolThreadCache threadCache() {
603         PoolThreadCache cache =  threadCache.get();
604         assert cache != null;
605         return cache;
606     }
607 
608     /**
609      * Returns the status of the allocator (which contains all metrics) as string. Be aware this may be expensive
610      * and so should not called too frequently.
611      */
612     public String dumpStats() {
613         int heapArenasLen = heapArenas == null ? 0 : heapArenas.length;
614         StringBuilder buf = new StringBuilder(512)
615                 .append(heapArenasLen)
616                 .append(" heap arena(s):")
617                 .append(StringUtil.NEWLINE);
618         if (heapArenasLen > 0) {
619             for (PoolArena<byte[]> a: heapArenas) {
620                 buf.append(a);
621             }
622         }
623 
624         int directArenasLen = directArenas == null ? 0 : directArenas.length;
625 
626         buf.append(directArenasLen)
627            .append(" direct arena(s):")
628            .append(StringUtil.NEWLINE);
629         if (directArenasLen > 0) {
630             for (PoolArena<ByteBuffer> a: directArenas) {
631                 buf.append(a);
632             }
633         }
634 
635         return buf.toString();
636     }
637 }