Netty低版本死循环问题导致cpu打满

一、当前现状

1.1 当前版本

几乎所有应用都依赖的有Netty低版本,SpringBoot 2.0.1版本默认依赖的就是低版本的Netty。
 

1.2 问题现象

4.1.23.Final低版本SDK存在CPU跑满100%的风险,导致应用不可用或自动重启。
 

1.3 原因分析

低版本ObjectCleaner类源码中存在死循环 / 空跑的逻辑。
  • 低版本4.1.23.Final源码缺陷分析
    private static final Runnable CLEANER_TASK = new Runnable() {
        @Override
        public void run() {
            boolean interrupted = false;
            for (;;) { // ❌ 外层无限循环
                // 只要 LIVE_SET 不为空,就一直循环
                while (!LIVE_SET.isEmpty()) { 
                    AutomaticCleanerReference reference;
                    try {
                        // 带超时拉取虚引用
                        reference = (AutomaticCleanerReference) REFERENCE_QUEUE.poll(REFERENCE_QUEUE_POLL_TIMEOUT_MS);
                    } catch (InterruptedException ex) {
                        interrupted = true;
                        continue;
                    }
                    if (reference != null) {
                        try {
                            reference.cleanup(); // 执行资源释放(堆外内存、Recycler、FastThreadLocal回收)
                        } catch (Throwable ignored) {
                            // ❌ 致命BUG:捕获异常后,没有移除 LIVE_SET 中的引用
                            // 引用永远残留在集合,!LIVE_SET.isEmpty() 恒为true
                        }                         
                        LIVE_SET.remove(reference);
                    }
                    // ❌ 当 reference == null(队列空),无休眠,直接下一轮循环 → 空轮询
                }
                // ❌ 高并发下 “空瞬间” 被新分配打破,LIVE_SET刚空,新堆外内存立刻加入,永远无法触发break;
                if (LIVE_SET.isEmpty() || !CLEANER_RUNNING.compareAndSet(false, true)) {
                    break;
                }
            }
        }
    };
 

二、解决方案

2.1 升级 Netty 版本

  • 升级至 4.1.68.Final 及以上,在pom.xml文件<dependencyManagement>中统一定义netty依赖版本。
依赖说明:netty-bom依赖必须放在dependencyManagement最前面,要不然会被覆盖不生效。
<properties>
    <netty.version>4.1.68.Final</netty.version>
</properties>

<dependencyManagement>
    <dependencies>
        <!-- 必须放在dependencyManagement最前面,要不然会被覆盖不生效!!! -->
<dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-bom</artifactId>
            <version>${netty.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>${spring-boot.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring-cloud.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
 

三、Git Case参考

https://github.com/netty/netty/issues/8873
 
 
 
posted @ 2026-06-29 14:11  六小扛把子  阅读(4)  评论(0)    收藏  举报