gpt4 book ai didi

java - 监控、调试和跟踪 CompletableFuture 任务

转载 作者:行者123 更新时间:2023-12-01 16:46:43 29 4
gpt4 key购买 nike

我想在使用 CompletableFuture 时监视、跟踪和调试我的任务,例如以下代码:

CompletableFuture.supplyAsync(() -> 2)
.thenApply(i -> i*2)
.thenAccept(i -> System.out.println("i = " + i));

CompletableFuture.AsynchronousCompletionTask 的 Javadoc看起来很有希望,但尚不清楚如何使用它:

A marker interface identifying asynchronous tasks produced by async methods. This may be useful for monitoring, debugging, and tracking asynchronous activities.

最佳答案

传递给执行器的Runnables将不是原来的Runnables,它们将被包装到一个实现AsynchronousCompletionTask的类中,这使得跟踪成为可能,如以下代码所示:

public class Main {
private static final Executor tracker = new TrackingExecutor(ForkJoinPool.commonPool());

public static void main(String[] args) throws InterruptedException {
CompletableFuture.supplyAsync(() -> 2, tracker)
.thenApply(i -> i*2)
.thenAccept(i -> System.out.println("i = " + i));
Thread.sleep(1000);
}
}

class TrackingExecutor implements Executor {
private Executor delegate;

public TrackingExecutor(Executor delegate) {
this.delegate = delegate;
}

@Override
public void execute(Runnable task) {
if(task instanceof CompletableFuture.AsynchronousCompletionTask) {
System.out.println("executing CompletableFuture task");
}
delegate.execute(task);
}
}

关于java - 监控、调试和跟踪 CompletableFuture 任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61759182/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com