聊聊ExecutorService的监控(executive.)
toyiye 2024-09-16 06:11 3 浏览 0 评论
序
本文主要研究一下ExecutorService的监控
InstrumentedExecutorService
metrics-core-4.0.2-sources.jar!/com/codahale/metrics/InstrumentedExecutorService.java
/** * An {@link ExecutorService} that monitors the number of tasks submitted, running, * completed and also keeps a {@link Timer} for the task duration. * <p/> * It will register the metrics using the given (or auto-generated) name as classifier, e.g: * "your-executor-service.submitted", "your-executor-service.running", etc. */ public class InstrumentedExecutorService implements ExecutorService { private static final AtomicLong NAME_COUNTER = new AtomicLong(); private final ExecutorService delegate; private final Meter submitted; private final Counter running; private final Meter completed; private final Timer idle; private final Timer duration; /** * Wraps an {@link ExecutorService} uses an auto-generated default name. * * @param delegate {@link ExecutorService} to wrap. * @param registry {@link MetricRegistry} that will contain the metrics. */ public InstrumentedExecutorService(ExecutorService delegate, MetricRegistry registry) { this(delegate, registry, "instrumented-delegate-" + NAME_COUNTER.incrementAndGet()); } /** * Wraps an {@link ExecutorService} with an explicit name. * * @param delegate {@link ExecutorService} to wrap. * @param registry {@link MetricRegistry} that will contain the metrics. * @param name name for this executor service. */ public InstrumentedExecutorService(ExecutorService delegate, MetricRegistry registry, String name) { this.delegate = delegate; this.submitted = registry.meter(MetricRegistry.name(name, "submitted")); this.running = registry.counter(MetricRegistry.name(name, "running")); this.completed = registry.meter(MetricRegistry.name(name, "completed")); this.idle = registry.timer(MetricRegistry.name(name, "idle")); this.duration = registry.timer(MetricRegistry.name(name, "duration")); } @Override public void execute(Runnable runnable) { submitted.mark(); delegate.execute(new InstrumentedRunnable(runnable)); } @Override public Future<?> submit(Runnable runnable) { submitted.mark(); return delegate.submit(new InstrumentedRunnable(runnable)); } @Override public <T> Future<T> submit(Runnable runnable, T result) { submitted.mark(); return delegate.submit(new InstrumentedRunnable(runnable), result); } @Override public <T> Future<T> submit(Callable<T> task) { submitted.mark(); return delegate.submit(new InstrumentedCallable<>(task)); } @Override public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException { submitted.mark(tasks.size()); Collection<? extends Callable<T>> instrumented = instrument(tasks); return delegate.invokeAll(instrumented); } @Override public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException { submitted.mark(tasks.size()); Collection<? extends Callable<T>> instrumented = instrument(tasks); return delegate.invokeAll(instrumented, timeout, unit); } @Override public <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws ExecutionException, InterruptedException { submitted.mark(tasks.size()); Collection<? extends Callable<T>> instrumented = instrument(tasks); return delegate.invokeAny(instrumented); } @Override public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws ExecutionException, InterruptedException, TimeoutException { submitted.mark(tasks.size()); Collection<? extends Callable<T>> instrumented = instrument(tasks); return delegate.invokeAny(instrumented, timeout, unit); } private <T> Collection<? extends Callable<T>> instrument(Collection<? extends Callable<T>> tasks) { final List<InstrumentedCallable<T>> instrumented = new ArrayList<>(tasks.size()); for (Callable<T> task : tasks) { instrumented.add(new InstrumentedCallable<>(task)); } return instrumented; } @Override public void shutdown() { delegate.shutdown(); } @Override public List<Runnable> shutdownNow() { return delegate.shutdownNow(); } @Override public boolean isShutdown() { return delegate.isShutdown(); } @Override public boolean isTerminated() { return delegate.isTerminated(); } @Override public boolean awaitTermination(long l, TimeUnit timeUnit) throws InterruptedException { return delegate.awaitTermination(l, timeUnit); } //...... }
- InstrumentedExecutorService实现了ExecutorService,对jdk原始的ExecutorService进行了包装,对相应的方法织入指标统计
- 主要统计了已提交的任务submitted(Meter),运行中的任务running(Counter),完成的任务completed(Meter),空闲时长idle(Timer),运行时长duration(Timer)
- 为了统计后面几个指标,需要对Runnable以及Callable进行织入,因而引入了InstrumentedRunnable、InstrumentedCallable
InstrumentedRunnable
private class InstrumentedRunnable implements Runnable { private final Runnable task; private final Timer.Context idleContext; InstrumentedRunnable(Runnable task) { this.task = task; this.idleContext = idle.time(); } @Override public void run() { idleContext.stop(); running.inc(); final Timer.Context durationContext = duration.time(); try { task.run(); } finally { durationContext.stop(); running.dec(); completed.mark(); } } }
- 织入了对idle、duration、running、completed的统计
InstrumentedCallable
private class InstrumentedCallable<T> implements Callable<T> { private final Callable<T> callable; InstrumentedCallable(Callable<T> callable) { this.callable = callable; } @Override public T call() throws Exception { running.inc(); final Timer.Context context = duration.time(); try { return callable.call(); } finally { context.stop(); running.dec(); completed.mark(); } } }
- 织入了对duration、running、completed的统计
ExecutorServiceMetrics
micrometer-core-1.0.3-sources.jar!/io/micrometer/core/instrument/binder/jvm/ExecutorServiceMetrics.java
/** * Monitors the status of executor service pools. Does not record timings on operations executed in the {@link ExecutorService}, * as this requires the instance to be wrapped. Timings are provided separately by wrapping the executor service * with {@link TimedExecutorService}. * * @author Jon Schneider * @author Clint Checketts */ @NonNullApi @NonNullFields public class ExecutorServiceMetrics implements MeterBinder { @Nullable private final ExecutorService executorService; private final Iterable<Tag> tags; public ExecutorServiceMetrics(@Nullable ExecutorService executorService, String executorServiceName, Iterable<Tag> tags) { this.executorService = executorService; this.tags = Tags.concat(tags, "name", executorServiceName); } //...... /** * Record metrics on the use of an {@link Executor}. * * @param registry The registry to bind metrics to. * @param executor The executor to instrument. * @param executorName Will be used to tag metrics with "name". * @param tags Tags to apply to all recorded metrics. * @return The instrumented executor, proxied. */ public static Executor monitor(MeterRegistry registry, Executor executor, String executorName, Iterable<Tag> tags) { if (executor instanceof ExecutorService) { return monitor(registry, (ExecutorService) executor, executorName, tags); } return new TimedExecutor(registry, executor, executorName, tags); } /** * Record metrics on the use of an {@link ExecutorService}. * * @param registry The registry to bind metrics to. * @param executor The executor to instrument. * @param executorServiceName Will be used to tag metrics with "name". * @param tags Tags to apply to all recorded metrics. * @return The instrumented executor, proxied. */ public static ExecutorService monitor(MeterRegistry registry, ExecutorService executor, String executorServiceName, Iterable<Tag> tags) { new ExecutorServiceMetrics(executor, executorServiceName, tags).bindTo(registry); return new TimedExecutorService(registry, executor, executorServiceName, tags); } @Override public void bindTo(MeterRegistry registry) { if (executorService == null) { return; } String className = executorService.getClass().getName(); if (executorService instanceof ThreadPoolExecutor) { monitor(registry, (ThreadPoolExecutor) executorService); } else if (className.equals("java.util.concurrent.Executors$DelegatedScheduledExecutorService")) { monitor(registry, unwrapThreadPoolExecutor(executorService, executorService.getClass())); } else if (className.equals("java.util.concurrent.Executors$FinalizableDelegatedExecutorService")) { monitor(registry, unwrapThreadPoolExecutor(executorService, executorService.getClass().getSuperclass())); } else if (executorService instanceof ForkJoinPool) { monitor(registry, (ForkJoinPool) executorService); } } private void monitor(MeterRegistry registry, @Nullable ThreadPoolExecutor tp) { if (tp == null) { return; } FunctionCounter.builder("executor.completed", tp, ThreadPoolExecutor::getCompletedTaskCount) .tags(tags) .description("The approximate total number of tasks that have completed execution") .baseUnit("tasks") .register(registry); Gauge.builder("executor.active", tp, ThreadPoolExecutor::getActiveCount) .tags(tags) .description("The approximate number of threads that are actively executing tasks") .baseUnit("threads") .register(registry); Gauge.builder("executor.queued", tp, tpRef -> tpRef.getQueue().size()) .tags(tags) .description("The approximate number of threads that are queued for execution") .baseUnit("threads") .register(registry); Gauge.builder("executor.pool.size", tp, ThreadPoolExecutor::getPoolSize) .tags(tags) .description("The current number of threads in the pool") .baseUnit("threads") .register(registry); } //...... }
- ExecutorServiceMetrics实现了MeterBinder接口,另外提供了静态方法来创建带有监控指标的ExecutorService,该静态方法命名为monitor,非常形象
- monitor方法首先创建ExecutorServiceMetrics,并bindTo了MeterRegistry,然后返回TimedExecutorService
- bindTo方法上报了executor.completed(FunctionCounter),executor.active(Gauge),executor.queued(Gauge),executor.pool.size(Gauge)这几个指标
TimedExecutorService
micrometer-core-1.0.3-sources.jar!/io/micrometer/core/instrument/internal/TimedExecutorService.java
/** * An {@link java.util.concurrent.ExecutorService} that is timed * * @author Jon Schneider */ public class TimedExecutorService implements ExecutorService { private final ExecutorService delegate; private final Timer timer; public TimedExecutorService(MeterRegistry registry, ExecutorService delegate, String executorServiceName, Iterable<Tag> tags) { this.delegate = delegate; this.timer = registry.timer("executor", Tags.concat(tags ,"name", executorServiceName)); } @Override public void shutdown() { delegate.shutdown(); } @Override public List<Runnable> shutdownNow() { return delegate.shutdownNow(); } @Override public boolean isShutdown() { return delegate.isShutdown(); } @Override public boolean isTerminated() { return delegate.isTerminated(); } @Override public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { return delegate.awaitTermination(timeout, unit); } @Override public <T> Future<T> submit(Callable<T> task) { return delegate.submit(timer.wrap(task)); } @Override public <T> Future<T> submit(Runnable task, T result) { return delegate.submit(() -> timer.record(task), result); } @Override public Future<?> submit(Runnable task) { return delegate.submit(() -> timer.record(task)); } @Override public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException { return delegate.invokeAll(wrapAll(tasks)); } @Override public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException { return delegate.invokeAll(wrapAll(tasks), timeout, unit); } @Override public <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException { return delegate.invokeAny(wrapAll(tasks)); } @Override public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return delegate.invokeAny(wrapAll(tasks), timeout, unit); } @Override public void execute(Runnable command) { delegate.execute(timer.wrap(command)); } private <T> Collection<? extends Callable<T>> wrapAll(Collection<? extends Callable<T>> tasks) { return tasks.stream().map(timer::wrap).collect(toList()); } }
- 对ExecutorService进行包装,增加了
Timer.record
micrometer-core-1.0.3-sources.jar!/io/micrometer/core/instrument/Timer.java
/** * Executes the runnable `f` and records the time taken. * * @param f Function to execute and measure the execution time. */ void record(Runnable f); /** * Wrap a {@link Runnable} so that it is timed when invoked. * * @param f The Runnable to time when it is invoked. * @return The wrapped Runnable. */ default Runnable wrap(Runnable f) { return () -> record(f); } /** * Wrap a {@link Callable} so that it is timed when invoked. * * @param f The Callable to time when it is invoked. * @param <T> The return type of the callable. * @return The wrapped callable. */ default <T> Callable<T> wrap(Callable<T> f) { return () -> recordCallable(f); }
- warp方法主要是包装调用record方法,而record由实现类去实现
AbstractTimer
micrometer-core-1.0.3-sources.jar!/io/micrometer/core/instrument/AbstractTimer.java
@Override public void record(Runnable f) { final long s = clock.monotonicTime(); try { f.run(); } finally { final long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } } @Override public final void record(long amount, TimeUnit unit) { if (amount >= 0) { histogram.recordLong(TimeUnit.NANOSECONDS.convert(amount, unit)); recordNonNegative(amount, unit); if (intervalEstimator != null) { intervalEstimator.recordInterval(clock.monotonicTime()); } } }
- record采用histogram进行统计
小结
dropwizard及micrometer均提供了对ExecutorService的指标统计的包装,micrometer则更近一步提供了静态方法来直接创建,非常方便。
相关推荐
- 为何越来越多的编程语言使用JSON(为什么编程)
-
JSON是JavascriptObjectNotation的缩写,意思是Javascript对象表示法,是一种易于人类阅读和对编程友好的文本数据传递方法,是JavaScript语言规范定义的一个子...
- 何时在数据库中使用 JSON(数据库用json格式存储)
-
在本文中,您将了解何时应考虑将JSON数据类型添加到表中以及何时应避免使用它们。每天?分享?最新?软件?开发?,Devops,敏捷?,测试?以及?项目?管理?最新?,最热门?的?文章?,每天?花?...
- MySQL 从零开始:05 数据类型(mysql数据类型有哪些,并举例)
-
前面的讲解中已经接触到了表的创建,表的创建是对字段的声明,比如:上述语句声明了字段的名称、类型、所占空间、默认值和是否可以为空等信息。其中的int、varchar、char和decimal都...
- JSON对象花样进阶(json格式对象)
-
一、引言在现代Web开发中,JSON(JavaScriptObjectNotation)已经成为数据交换的标准格式。无论是从前端向后端发送数据,还是从后端接收数据,JSON都是不可或缺的一部分。...
- 深入理解 JSON 和 Form-data(json和formdata提交区别)
-
在讨论现代网络开发与API设计的语境下,理解客户端和服务器间如何有效且可靠地交换数据变得尤为关键。这里,特别值得关注的是两种主流数据格式:...
- JSON 语法(json 语法 priority)
-
JSON语法是JavaScript语法的子集。JSON语法规则JSON语法是JavaScript对象表示法语法的子集。数据在名称/值对中数据由逗号分隔花括号保存对象方括号保存数组JS...
- JSON语法详解(json的语法规则)
-
JSON语法规则JSON语法是JavaScript对象表示法语法的子集。数据在名称/值对中数据由逗号分隔大括号保存对象中括号保存数组注意:json的key是字符串,且必须是双引号,不能是单引号...
- MySQL JSON数据类型操作(mysql的json)
-
概述mysql自5.7.8版本开始,就支持了json结构的数据存储和查询,这表明了mysql也在不断的学习和增加nosql数据库的有点。但mysql毕竟是关系型数据库,在处理json这种非结构化的数据...
- JSON的数据模式(json数据格式示例)
-
像XML模式一样,JSON数据格式也有Schema,这是一个基于JSON格式的规范。JSON模式也以JSON格式编写。它用于验证JSON数据。JSON模式示例以下代码显示了基本的JSON模式。{"...
- 前端学习——JSON格式详解(后端json格式)
-
JSON(JavaScriptObjectNotation)是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。它基于JavaScriptProgrammingLa...
- 什么是 JSON:详解 JSON 及其优势(什么叫json)
-
现在程序员还有谁不知道JSON吗?无论对于前端还是后端,JSON都是一种常见的数据格式。那么JSON到底是什么呢?JSON的定义...
- PostgreSQL JSON 类型:处理结构化数据
-
PostgreSQL提供JSON类型,以存储结构化数据。JSON是一种开放的数据格式,可用于存储各种类型的值。什么是JSON类型?JSON类型表示JSON(JavaScriptO...
- JavaScript:JSON、三种包装类(javascript 包)
-
JOSN:我们希望可以将一个对象在不同的语言中进行传递,以达到通信的目的,最佳方式就是将一个对象转换为字符串的形式JSON(JavaScriptObjectNotation)-JS的对象表示法...
- Python数据分析 只要1分钟 教你玩转JSON 全程干货
-
Json简介:Json,全名JavaScriptObjectNotation,JSON(JavaScriptObjectNotation(记号、标记))是一种轻量级的数据交换格式。它基于J...
- 比较一下JSON与XML两种数据格式?(json和xml哪个好)
-
JSON(JavaScriptObjectNotation)和XML(eXtensibleMarkupLanguage)是在日常开发中比较常用的两种数据格式,它们主要的作用就是用来进行数据的传...
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- r语言矩阵 (127)
- browsererror (114)
- exportexcel (119)
- cv2.bitwise_not (137)
- dump命令 (128)
- es6concat (126)
- heapify (127)
- java.security.egd (130)
- javax.annotation (117)
- jsstringsplit (117)
- js数字 (115)
- maven编译 (132)
- mysqlleft (128)
- nodejsbuffer (149)
- org.apache.commons.httpclient (126)
- org.jsoup (141)
- org.springframework.web (128)
- robotframework-ride (115)
- setnocounton (141)
- socket.gethostbyname (122)
- sqlmid (121)
- time.strptime (133)
- vscode格式化 (125)
- win32con (129)
- window.localstorage (126)