监视、调试和跟踪 CompletableFuture 任务

Monitoring, debugging, and tracking CompletableFuture tasks

我想在使用 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的class,这使得跟踪成为可能,如下代码所示:

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);
    }
}