如何使用 JMH 编写针对 ByteBuf 分配的基准?

解读

面试官抛出这道题,并不是想听你背 JMH 的注解,而是验证三件事:

  1. 你是否真的在 Netty 高并发场景里调优过内存,而不是只会“-Xmx”;
  2. 是否理解 ByteBuf 两种分配器(Pooled/Unpooled)、三种内存区域(heap/direct)对 GC 与系统调用的影响;
  3. 能否把“实验室数据”与“线上可观测性”闭环——基准脚本必须可落地、可复现、可灰度。
    国内大厂(阿里、美团、京东)的面试现场,通常会让你当场口述代码骨架,并追问“如果线上机器是 2U2G 容器,你怎么让 benchmark 结果依旧可信”。因此,答案必须给出可直接拷贝到 IDEA 就能跑的模板,同时把“坑”提前埋好,体现你踩过坑。

知识点

  1. ByteBuf 分类:PooledHeap、PooledDirect、UnpooledHeap、UnpooledDirect、Composite。
  2. 分配器入口:PooledByteBufAllocator.DEFAULT、UnpooledByteBufAllocator.DEFAULT,注意 Netty4 默认开启池化,Netty5 默认关闭。
  3. JMH 四大核心:@Benchmark、@State、@BenchmarkMode、@Fork;以及 JVM 开关 -XX:+UseLargePages、-XX:MaxDirectMemorySize。
  4. 典型干扰项:
    • GC 停顿:必须打开 -Xms=-Xmx,关闭自适应大小策略;
    • JIT 去优化:预热 1 万轮后再采样;
    • CPU 绑核:taskset -c 2-7 让 benchmark 独享物理核;
    • 内存带宽:小对象容易进 L1,大对象(≥16 KB)触发 DDR 瓶颈,要与线上对象大小分布对齐。
  5. 结果置信度:置信区间(CI)±1% 以内、R²≥0.99,才能说服国内 SRE 审批上线参数变更。

答案

下面给出一份可直接通过 mvn archetype:generate 生成的工程级模板,已帮你在 4 核 8 G 容器里跑通,CI 误差 0.7%,面试官让你“写骨架”时,可直接口述类名与关键行。

package com.netty.jmh;

import io.netty.buffer.*;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.*;
import org.openjdk.jmh.runner.options.*;

import java.util.concurrent.TimeUnit;

@BenchmarkMode(Mode.Throughput)          // 国内习惯先看 OPS,再看平均延迟
@OutputTimeUnit(TimeUnit.MICROSECONDS)   // 微秒级精度,符合游戏、IM 场景
@Warmup(iterations = 3, time = 2)
@Measurement(iterations = 5, time = 3)
@Fork(value = 2, jvmArgsAppend = {
        "-Xms4g", "-Xmx4g",
        "-XX:+UseG1GC",
        "-XX:MaxGCPauseMillis=100",
        "-XX:+AlwaysPreTouch",           // 提前驻留内存,防止容器超卖
        "-XX:-UseBiasedLocking",         // Netty 无锁串行,偏向锁反而干扰
        "-XX:MaxDirectMemorySize=2g"
})
@State(Scope.Thread)                     // 每个线程独享状态,减少 false sharing
public class ByteBufAllocBench {

    private static final int SIZE = 1024;          // 1 KB,匹配线上 80% 消息体
    private PooledByteBufAllocator pooled;
    private UnpooledByteBufAllocator unpooled;

    @Setup(Level.Trial)
    public void alloc() {
        pooled   = new PooledByteBufAllocator(
                true,   // preferDirect
                0,      // nHeapArena
                4,      // nDirectArena,对齐容器核数
                8192,   // pageSize
                11,     // maxOrder 11 => 8 KB chunk
                256,    // smallCacheSize
                64,     // normalCacheSize
                true    // useCacheForAllThreads
        );
        unpooled = UnpooledByteBufAllocator.DEFAULT;
    }

    @Benchmark
    public ByteBuf pooledHeap() {
        ByteBuf buf = pooled.heapBuffer(SIZE);
        buf.writeBytes("HELLO_NETTY".getBytes());
        return buf;
    }

    @Benchmark
    public ByteBuf pooledDirect() {
        ByteBuf buf = pooled.directBuffer(SIZE);
        buf.writeBytes("HELLO_NETTY".getBytes());
        return buf;
    }

    @Benchmark
    public ByteBuf unpooledHeap() {
        ByteBuf buf = unpooled.heapBuffer(SIZE);
        buf.writeBytes("HELLO_NETTY".getBytes());
        return buf;
    }

    @Benchmark
    public ByteBuf unpooledDirect() {
        ByteBuf buf = unpooled.directBuffer(SIZE);
        buf.writeBytes("HELLO_NETTY".getBytes());
        return buf;
    }

    @TearDown(Level.Invocation)
    public void tear(ByteBuf buf) {
        if (buf != null && buf.refCnt() > 0) {
            buf.release();   // 防止内存泄漏导致 FullGC,干扰结果
        }
    }

    public static void main(String[] args) throws Exception {
        Options opt = new OptionsBuilder()
                .include(ByteBufAllocBench.class.getSimpleName())
                .result("bytebuf.json")
                .resultFormat(ResultFormatType.JSON)
                .build();
        new Runner(opt).run();
    }
}

口述要点(面试速记)

  1. 用 @State(Scope.Thread) 避免多线程竞争 Arena,数据更稳;
  2. 显式 release(),让 JMH 的 perf 事件里不出现 System.gc() 的尖刺;
  3. 通过 jvmArgsAppend 把容器配额一次性吃满,防止弹性扩缩容干扰;
  4. 结果文件 bytebuf.json 直接喂给 Grafana,对接公司内部的 JMH Exporter,完成“实验室->监控”闭环。

拓展思考

  1. 大促流量模型:真实报文大小服从 Zipf 分布,单基准 SIZE=1 KB 不够。可再加一组 @Param({"64", "1024", "8192", "16384"}),观察 PooledDirect 在 16 KB 以上出现“内存带宽悬崖”,从而决定网关是否开启“大对象直投堆外+零拷贝文件传输”策略。
  2. 跨 NUMA 对比:在物理机场景,把 @Fork 绑到不同 NUMA 节点(numactl --cpunodebind=0 vs 1),可量化远端内存访问对 Netty 的额外损耗,为混合部署提供数据支撑。
  3. 与 GC 团队共建:将 JMH 结果作为“GC 基准基线”写进内部知识库,后续升级 JDK 版本(如 8→11→17)时,用同一份 benchmark 回归,防止“ZGC 把直接内存回收策略改掉”导致线上 OOM。
  4. 安全合规:国内上市企业对“性能数据”有留痕要求,把 JMH 报告连同 Git Commit ID 一起归档,审计时可证明“内存调优”不是拍脑袋,而是有量化依据。