Java Executor 执行器的监控与调试方法
一 关键指标与采集方式
二 任务级监控与结果收集
三 运行期调试与问题定位
四 生产级监控落地与告警建议
五 最小可用示例代码
import java.util.concurrent.*;
public class ExecutorMonitorDemo {
public static void main(String[] args) throws InterruptedException {
// 1) 可观测的线程池:显式参数 + 有界队列 + 拒绝策略
ThreadPoolExecutor pool = new ThreadPoolExecutor(
2, 4, 60, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(10),
new ThreadFactory() {
private final ThreadFactory df = Executors.defaultThreadFactory();
public Thread newThread(Runnable r) {
Thread t = df.newThread(r);
t.setName("worker-" + t.getId());
t.setDaemon(false);
return t;
}
},
new ThreadPoolExecutor.CallerRunsPolicy()
);
// 2) 定时监控
ScheduledExecutorService monitor = Executors.newScheduledThreadPool(1);
monitor.scheduleAtFixedRate(() -> {
System.out.printf("[METRIC] pool=%d/%d, active=%d, completed=%d, queued=%d, largest=%d%n",
pool.getPoolSize(), pool.getMaximumPoolSize(),
pool.getActiveCount(),
pool.getCompletedTaskCount(),
pool.getQueue().size(),
pool.getLargestPoolSize());
}, 0, 5, TimeUnit.SECONDS);
// 3) 提交一批任务并用 CompletionService 按完成顺序获取
CompletionService<Integer> cs = new ExecutorCompletionService<>(pool);
int taskCount = 10;
CountDownLatch latch = new CountDownLatch(taskCount);
for (int i = 0; i < taskCount; i++) {
final int idx = i;
cs.submit(() -> {
try {
TimeUnit.MILLISECONDS.sleep(500 + (long) (Math.random() * 1500));
return idx * 2;
} finally {
latch.countDown();
}
});
}
// 4) 消费已完成任务
for (int i = 0; i < taskCount; i++) {
try {
Future<Integer> f = cs.take();
System.out.println("Completed result: " + f.get());
} catch (InterruptedException | ExecutionException e) {
Thread.currentThread().interrupt();
e.printStackTrace();
}
}
// 5) 等待全部任务收尾并关闭
latch.await();
pool.shutdown();
if (!pool.awaitTermination(10, TimeUnit.SECONDS)) {
pool.shutdownNow();
}
monitor.shutdownNow();
}
}
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。