【问题标题】:How to get Direct Memory Snapshot of a Netty 4 Application如何获取 Netty 4 应用程序的直接内存快照
【发布时间】:2018-09-04 19:24:06
【问题描述】:

我有一个基于 Netty 的服务器,它异步处理大量 HTTP 请求。

目标 - 公开应用程序的直接内存使用情况。

现在我明白引用计数是一种暴露内存使用的方法。 但是对于每个请求,很少有对象(如 httpContent 等)被显式保留,而对于其他对象,Netty 会在内部更新引用计数。

  1. 由于服务器能够一次处理大量请求,我如何监控应用程序的直接内存使用情况并将其公开?

  2. 有没有办法获取整个应用程序的总引用计数?

  3. 除了 ReferenceCount,还有哪些其他方法可以监控直接内存使用情况?

【问题讨论】:

    标签: java memory netty reference-counting directmemory


    【解决方案1】:

    Netty 默认使用ByteBufAllocator.DEFAULT(实际上是ByteBufUtil.DEFAULT_ALLOCATOR,即UnpooledByteBufAllocator.DEFAULTPooledByteBufAllocator.DEFAULT)分配器进行分配。如果您没有在代码中明确设置另一个分配器,您可以使用它来跟踪您的内存消耗。

    你可以用下面的代码做到这一点:

    public class MemoryStat {
    
        public final long heapBytes;
    
        public final long directBytes;
    
        public MemoryStat(ByteBufAllocator byteBufAllocator) {
            long directMemory = 0;
            long heapMemory = 0;
    
            if (byteBufAllocator instanceof ByteBufAllocatorMetricProvider) {
                ByteBufAllocatorMetric metric = ((ByteBufAllocatorMetricProvider) byteBufAllocator).metric();
                directMemory = metric.usedDirectMemory();
                heapMemory = metric.usedHeapMemory();
            }
    
            this.directBytes = directMemory;
            this.heapBytes = heapMemory;
        }
    }
    

    用法:new MemoryStat(ByteBufAllocator.DEFAULT);

    两个默认的网络分配器UnpooledByteBufAllocatorPooledByteBufAllocator实现ByteBufAllocatorMetricProvider 提供2种方法:

    public interface ByteBufAllocatorMetric {
        /**
         * Returns the number of bytes of heap memory used by a {@link ByteBufAllocator} or {@code -1} if unknown.
         */
        long usedHeapMemory();
    
        /**
         * Returns the number of bytes of direct memory used by a {@link ByteBufAllocator} or {@code -1} if unknown.
         */
        long usedDirectMemory();
    }
    

    没有直接的 API 来获取总引用计数。

    【讨论】:

    • 这太好了,我今天早些时候在检查 Netty Git 时上了这些课程。 (github.com/netty/netty) 并且正在浏览文档以查看它们的用法。感谢您缩短我的潜水时间 :) P.S - 我使用的是早期版本的 Netty 4.1,它之前没有这些新的“度量”类。但是有 dumpStats() 和其他非常少的方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多