Apache License 2.0

技术解读

以下内容由 GitRead 中文社区 编辑团队基于项目 README 与官方资料整理, 结合中文开发者的常见使用场景补充技术选型建议。具体以项目官方文档为准。

深度技术分析:dromara/dynamic-tp

项目背景与痛点

随着微服务架构的日益普及,异步任务调度和并发控制变得愈发重要。传统的线程池实现较为僵化,无法满足高度可变的并发处理需求。此外,监控和报警系统分散独立,不同配置中心的统一管理也存在挑战。dromara/dynamic-tp 正是为解决这些问题而生的轻量级框架,它提供了动态管理线程池的能力,并集成了多种配置中心支持。

核心技术揭秘

dromara/dynamic-tp 的核心设计理念在于实现高灵活性的线程池管理和实时监控。它支持多种配置中心调用机制,涵盖了 Nacos、Apollo、Zookeeper、Consul、和 Etcd,这些中心均可通过 SPI(服务提供者接口)进行扩展。

通过内置的监控和报警机制,框架能够实时响应系统的动态变化,并对线程池容量进行智能化调整。此外,框架的架构设计允许第三方线程池的统一管理,提高了系统的稳定性和可靠性。

架构概览

接下来,我们通过一张架构图来了解其工作原理:

graph TD A[请求到达] --> B[动态线程池] B --> C[任务执行] C --> D{"任务完成?"} D -->|"是"| E[通知客户端] D -->|"否"| F[队列等待] G[配置中心] -.- H[动态调整] H --> B B --> I[监控报警]

从架构图中可以看出,框架的入口是请求到达,调度系统将根据需求自动选择或创建合适的线程池,任务成功或失败会进入不同的路径。同时,配置中心会根据系统状态动态调整线程池配置,而监控报警系统则会实时监控状态变化。

功能亮点与差异

dromara/dynamic-tp 的亮点在于集成了多种配置中心支持,允许开发者灵活地选择适合自己业务的方案,同时提供了监控和报警机制。相对于其他框架,它拥有更加全面的监控能力,并且支持广泛的配置中心调用,这意味着更少的开发工作量和更高的可扩展性。

应用场景与落地建议

在生产环境中使用 dromara/dynamic-tp 时,应注意配置中心的健康状态,确保其可以稳定提供配置信息。此外,根据业务规模的不同,可以适当调整线程池的初始大小和扩缩容策略。该框架适合需要动态调整资源使用量的复杂应用场景,例如多租户系统、流量突增的快速响应系统等。

综合评价

dromara/dynamic-tp 在灵活性、实时监控和配置中心支持方面表现突出,尤其适合微服务中的并发任务管理。值得肯定的是它的全面性和易维护性,但也需要注意监控报警机制的配置复杂性可能为一些开发者带来困扰。总体而言,这是一个高效且值得推荐的框架。

关于

GitHub 原始描述(英文)

A lightweight dynamic thread pool framework with built-in monitoring and alerting, unified third-party thread pool management, and support for popular configuration centers (Nacos, Apollo, Zookeeper, Consul, and Etcd), extensible via SPI。

描述取自 GitHub 官方 API,保持仓库作者书写的原文。

语言占比

C++
HTML
Java
Lua
Thrift

Release

README

logo

A lightweight dynamic thread pool based on configuration centers, with built-in monitoring & alerting, middleware thread pool management, and SPI extensibility

star

🌐 中文 | English

Website: https://dynamictp.cn 🔥


Pain Points

Have you encountered these issues when using ThreadPoolExecutor?

  1. You created a ThreadPoolExecutor, but have no idea what values to set for the core parameters.

  2. You set parameters based on experience, only to find after deployment that they need adjustment — requiring code changes and redeployment.

  3. Thread pools are a black box to developers. You can’t monitor their behavior until something breaks.

If so, DynamicTp may be the solution.

ThreadPoolExecutor provides set/get methods and extension points for its core parameters, enabling runtime dynamic modification.

👉 ThreadPoolExecutor dynamic methods (click to expand)
// --- Set ---
public void setCorePoolSize(int corePoolSize);                    // core pool size
public void setMaximumPoolSize(int maximumPoolSize);              // max pool size
public void setKeepAliveTime(long time, TimeUnit unit);           // thread idle keep-alive time
public void setThreadFactory(ThreadFactory threadFactory);        // thread factory
public void setRejectedExecutionHandler(RejectedExecutionHandler handler); // rejection policy
public void allowCoreThreadTimeOut(boolean value);                // allow core threads to time out

// --- Get ---
public int getCorePoolSize();
public int getMaximumPoolSize();
public long getKeepAliveTime(TimeUnit unit);
public BlockingQueue<Runnable> getQueue();                        // task queue
public RejectedExecutionHandler getRejectedExecutionHandler();
public boolean allowsCoreThreadTimeOut();

// --- Extension hooks ---
protected void beforeExecute(Thread t, Runnable r);               // before task execution
protected void afterExecute(Runnable r, Throwable t);             // after task execution

Most modern internet projects adopt microservice architecture with a service governance stack. The distributed configuration center plays a key role — enabling real-time configuration changes with instant effect.

So, can we combine a configuration center to dynamically adjust thread pool parameters at runtime?

Absolutely. Configuration centers are highly available, relieving concerns about config push failures and reducing the effort of building a dynamic thread pool solution from scratch.

Background summary:

  • Ubiquity: Thread pools are a fundamental tool used by 90%+ of Java developers to improve system performance.

  • Uncertainty: Projects often contain many thread pools — some IO-intensive, some CPU-intensive — and optimal core parameters are hard to determine upfront, requiring runtime tuning.

  • Lack of visibility: Thread pool metrics are invisible during operation. A monitoring & alerting mechanism is needed to detect issues before and during incidents.

  • High availability: Configuration changes must be reliably pushed to clients. Leveraging an existing configuration center greatly improves system availability.


Features

Based on the above analysis, we extended ThreadPoolExecutor with the following goals:

  1. Dynamic parameter modification at runtime, taking effect instantly.

  2. Real-time monitoring of thread pool status with alerting, pushing notifications to office platforms.

  3. Periodic metric collection, integrated with visualization platforms like Grafana for dashboards.

  4. Thread pool management for commonly used third-party middleware.

Latest version features: ✅

  • Zero code intrusion: All configuration lives in the configuration center. At startup, thread pools are created from config and registered in the Spring container — inject and use directly, zero impact on business code.

  • Lightweight & simple: Get started in 3 minutes with just 4 steps. Simply add the dependency, configure, annotate, and inject.

  • Notifications & alerting: Multiple alert dimensions (config change, thread activity, queue capacity, rejection, task execution/wait timeout). Supports WeCom, DingTalk, Feishu, Email, and extensible via SPI.

  • Monitoring: 20+ metrics (pool, queue, task, TPS, TPxx) collected via MicroMeter, JsonLog, JMX, or Spring Boot Endpoint. Extensible via SPI.

  • Task enhancement: Powerful task wrapping (stronger than Spring’s built-in). Implement TaskWrapper interface for MDC, TTL, trace context propagation (e.g., MdcTaskWrapper, TtlTaskWrapper, OpenTelemetryWrapper).

  • Multi configuration center support: Nacos, Apollo, Zookeeper, Consul, Etcd, Polaris, ServiceComb. Extensible via SPI.

  • Middleware thread pool management: Integrated with Tomcat, Jetty, Undertow, Dubbo, RocketMQ, Hystrix, gRPC, Motan, OkHttp3, Brpc, Tars, SofaRPC, RabbitMQ, Liteflow, Thrift (dynamic tuning, monitoring, alerting).

  • Multiple pool modes: DtpExecutor (enhanced), EagerDtpExecutor (IO-intensive), ScheduledDtpExecutor (scheduled), OrderedDtpExecutor (ordered). Choose based on your scenario.

  • Compatibility: Standard JUC thread pools and Spring ThreadPoolTaskExecutor can be managed by adding @DynamicTp on the @Bean definition.

  • Graceful shutdown: Leverages Spring lifecycle management to shut down thread pools gracefully, processing as many queued tasks as possible before shutdown.

  • Highly extensible: Core features expose SPI interfaces for custom implementations (config center, config parsing, alerting, metrics collection, task wrapping, rejection policies, etc.).

  • Battle-tested at scale: Inspired by Meituan’s thread pool practice, with mature production experience at Meituan.


Architecture

The framework is divided into the following modules:

  1. Configuration change listener

  2. Thread pool management

  3. Monitoring

  4. Notification & alerting

  5. Third-party middleware thread pool management

Architecture

See the official documentation for details: Architecture


Quick Start

  1. Add the dependency for your configuration center (see official docs).

  2. Configure thread pool instances in your configuration center (see official docs).

  3. Add @EnableDynamicTp annotation to your application class.

  4. Inject via @Resource / @Autowired, or retrieve with DtpRegistry.getExecutor("name").

For detailed examples, see the example module and the official documentation.


Alerting

  • Alert notifications are pushed when thresholds are triggered (thread activity, queue capacity, rejection, task wait/execution timeout), with highlighted fields.
Alert
  • Configuration change notifications are pushed with highlighted changed fields.
Config Change Notification

Monitoring

Monitoring Data 1 Monitoring Data 2 Monitoring Data 3

Four metric collection modes are available, configured via collectorTypes (default: Micrometer):

  1. Logging: Metrics output as JSON to a dedicated log file.

  2. Internal_logging: Metrics output as JSON to the application log.

  3. Micrometer: Uses the Micrometer facade to collect metrics into storage platforms (Prometheus, InfluxDB, etc.).

  4. Endpoint: Exposes a Spring Boot Endpoint for real-time metric retrieval via HTTP.

📖 See the official documentation for details: Alerting | Monitoring


Star History

Star History Chart


Repository


Contact

If you find this project helpful, please give us a star — your support drives us forward!

For questions, ideas, or suggestions, join our community to chat with 1700+ members.

Follow the WeChat public account and add my personal WeChat (note: dynamic-tp) to join the group.

To help the project grow, please register here: User Registration


Sponsors

  • Easysearch: Enterprise-grade distributed search database.

  • HertzBeat: An easy-to-use, real-time monitoring and alerting system with powerful custom monitoring capabilities, no Agent required.

评论

暂无评论