简体   繁体   English

如何为CompletableFutures提供ThreadLocal?

[英]How-to provide a ThreadLocal to CompletableFutures?

I need to provide a ThreadLocal to all the threads which end up running specific CompletableFuture.supplyAsync Suppliers. 我需要为最终运行特定CompletableFuture.supplyAsync供应商的所有线程提供ThreadLocal

From the javadoc I see that CompletableFuture uses " ForkJoinPool commonPool() " which very much fits my performance use case. 从javadoc我看到CompletableFuture使用“ ForkJoinPool commonPool() ”,它非常适合我的性能用例。

How do I transfer a ThreadLocal (and afterwards delete) to all pool threads running a specific CompletableFuture Supplier? 如何将ThreadLocal (以及之后的删除)传输到运行特定CompletableFuture供应商的所有池线程?

Remark: 备注:

I see that all CompletableFuture async completion methods accept an Executor. 我看到所有CompletableFuture async完成方法都接受Executor。 I would love to use the default ForkJoinPool commonPool() but if this is not possible I guess I have to override ThreadPoolExecutor and implement beforeExecute ? 我很想使用默认的ForkJoinPool commonPool()但如果这不可能,我想我必须覆盖ThreadPoolExecutor并实现beforeExecute

I guess you'll have to find your own way arround it as exec() on ForkJoinTask is protected. 我想你必须找到自己的方式,因为ForkJoinTask上的exec()受到保护。 For concrete implementations you can of course write your own wrapper. 对于具体实现,您当然可以编写自己的包装器。

This is what I would do for a single ThreadLocal and a Callable : 这就是我要为单个ThreadLocalCallable做的事情:

public static class WithThreadLocal<V, T> implements Callable<V> {
    private final ThreadLocal<T> threadLocal;
    private final T              value;
    private final Callable<V>    callable;


    public WithThreadLocal(ThreadLocal<T> threadLocal, T value, Callable<V> callable) {
        this.threadLocal = threadLocal;
        this.value = value;
        this.callable = callable;
    }

    @Override
    public V call() throws Exception {
        T oldValue = threadLocal.get();
        try {
            threadLocal.set(value);
            return callable.call();
        } finally {
            threadLocal.set(oldValue);
        }
    }
}

From there you can use ForkJoinTask.adapt() . 从那里你可以使用ForkJoinTask.adapt() Otherwise you might be interrested in https://stackoverflow.com/a/7260332/1266906 否则,您可能会对https://stackoverflow.com/a/7260332/1266906感兴趣

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM