在 Tomcat 10 中启用虚拟线程执行 Groovy 脚本

解读

国内主流互联网与金融企业已陆续将 JDK 21 与 Tomcat 10.1.x 纳入技术雷达,**虚拟线程(Project Loom)**被视为“高并发、低成本”的杀手锏。面试官抛出此题,并非单纯考察“会写 Groovy”,而是验证候选人能否把 Groovy 动态编译、类加载隔离、Tomcat 线程模型、JDK 21 虚拟线程调度器 四项技术栈打通,并给出可落地的工程方案。回答时务必体现:

  1. 让 Groovy 脚本真正运行在 虚拟线程调度器 而非传统 Thread;
  2. 对 Tomcat 10 的 Executor 体系零侵入或最小侵入;
  3. 兼顾 热加载、内存泄漏、安全沙箱 等国内生产环境硬性指标。

知识点

  1. 虚拟线程载体:JDK 21 的 java.lang.VirtualThread 由 ForkJoinPool 调度,无需池化,禁止与 ThreadLocal 滥用。
  2. Tomcat 10.1 线程扩展点:Executor 接口 + LifecycleListener 可替换默认 ThreadPoolExecutor。
  3. Groovy 动态类加载:GroovyClassLoader 每次 parseClass 会生成新类,需缓存并设置 parent=null 的隔离沙箱,防止 metaspace 泄漏。
  4. Servlet 3.1 异步模型:AsyncContext 必须显式调用 dispatch() 或 complete(),虚拟线程中执行耗时逻辑时仍需遵循该契约,否则连接会被容器强制回收。
  5. 国内合规:金融场景需通过 JEP 290 过滤器 限制反序列化;政务云要求 国密 TLS,虚拟线程内调用 SSLEngine 时需复用同一 ByteBuffer 避免膨胀。

答案

步骤一:构建虚拟线程 Executor

class VirtualThreadExecutor implements Executor, LifecycleListener {
    private volatile boolean started = false
    void start() { started = true }
    void stop()  { started = false }
    void execute(Runnable r) {
        if (!started) throw new RejectedExecutionException()
        Thread.ofVirtual().name("groovy-vt-", 0).unstarted(r).start()
    }
    void lifecycleEvent(LifecycleEvent event) {
        if (event.type == Lifecycle.AFTER_START_EVENT) start()
        if (event.type == Lifecycle.BEFORE_STOP_EVENT)  stop()
    }
}

步骤二:在 conf/server.xml 中替换默认线程池

<Executor name="tomcatVirtualExecutor"
          className="com.yourcorp.tomcat.VirtualThreadExecutor"/>
<Connector port="8080" protocol="org.apache.coyote.http11.Http11NioProtocol"
           executor="tomcatVirtualExecutor"/>

步骤三:Groovy 脚本热加载与虚拟线程绑定

@WebServlet(urlPatterns = "/groovy/api/*", asyncSupported = true)
class GroovyScriptDispatcher extends HttpServlet {
    private final GroovyClassLoader gcl = new GroovyClassLoader(
        null, // 隔离 parent
        new CompilerConfiguration().addCompilationCustomizers(
            new ASTTransformationCustomizer(CompileStatic.class)
        )
    )
    private final ConcurrentHashMap<String, Class<?>> cache = new ConcurrentHashMap<>()

    protected void service(HttpServletRequest req, HttpServletResponse resp) {
        def async = req.startAsync()
        Thread.ofVirtual().name("groovy-script").start {
            try {
                String scriptPath = req.pathInfo
                Class<?> clazz = cache.computeIfAbsent(scriptPath) { k ->
                    File scriptFile = new File("/app/groovy/scripts${k}.groovy")
                    gcl.parseClass(scriptFile)
                }
                def delegate = clazz.newInstance()
                delegate.binding = new Binding(request: req, response: resp)
                delegate.run()
            } catch (any) {
                resp.sendError(500, any.message)
            } finally {
                async.complete()
            }
        }
    }
}

步骤四:启动参数与验证

  • JDK 21+ 必须打开 --enable-preview 以激活虚拟线程;
  • 在 catalina.sh 加入 CATALINA_OPTS="$CATALINA_OPTS --enable-preview -Djdk.traceVirtualThreadLocals=true",方便排查 ThreadLocal 泄漏;
  • 使用 jcmd <pid> Thread.print 观察线程名前缀为 groovy-vt-* 的载体线程仅几十条,即证明脚本已运行在虚拟线程而非平台线程。

拓展思考

  1. 性能调优:虚拟线程的切换成本虽低,但 Groovy 动态调用仍需反射,可结合 Groovy 3.0 的 @CompileStatic 与 indy 指令 把热点脚本静态化,降低 CPU 30% 以上。
  2. 安全加固:国内等保 2.0 要求“动态语言执行必须沙箱化”,可在 GroovyClassLoader 之上再包一层 SecureASTCustomizer,禁用 System.exit、Runtime.exec 与反射访问 java.lang.Thread,防止脚本破坏容器。
  3. 弹性伸缩:虚拟线程数量无上限,但后端 JDBC 连接池仍是瓶颈。建议使用 Reactive 驱动(R2DBC)+ 虚拟线程调度器 做“线程数≈连接数”的 1:1 映射,避免传统池化导致的排队阻塞。
  4. 监控告警:Tomcat 10 自带 VirtualThreadExecutor MBean 尚未标准化,可自定义 Micrometer 指标,把 虚拟线程的 pinned 次数、Groovy 类加载次数、Metaspace 使用率 推送到 Prometheus,实现金融级秒级告警。