【问题标题】:Thread Pooling and InheritedThreadLocal线程池和 InheritedThreadLocal
【发布时间】:2013-08-08 14:45:19
【问题描述】:

我看过下面的问题。答案是改用信号量。这没有回答我面临的问题中所述的其他问题之一。

Using InheritableThreadLocal with ThreadPoolExecutor -- or -- a ThreadPoolExecutor that doesn't reuse threads

我有一个父线程,它为 InhertiedThreadLocal 中的每个新请求设置一些唯一标识符,并向 ThreadPool 提交 2 个可运行任务,即 2 个线程。 对于初始请求,在父线程中为 InheritedThreadLocal 设置的值会正确传播到 ChildThread。 对于接下来的请求,子线程没有接收到父线程设置的最新的 InheritedThreadLocal,而是使用了 ChildThread 中的旧值。

这是因为线程池重用线程,而 InheritedThreadLocal 仅在创建新线程时才被复制。

现在如何在线程池场景中将 InheritedThreadLocal 的最新值从父线程传播到子线程。 有没有办法解决这个问题?

【问题讨论】:

  • 我尝试了谷歌搜索,但如果可以解决,找不到具体的答案。
  • 我也面临同样的问题。你最后找到解决方法了吗?如果是,请将其添加为答案。
  • @rahulmohan 不知何故,我们没有继续执行上述要求,因此我们没有进一步尝试。stackoverflow.com/a/7297494/745018 如果它对您有帮助,请检查。
  • 重点是只有在创建子线程时,父线程的线程局部值才会传递给子线程。一旦这个子线程在初始执行后返回池中或从那里执行多次,它无法访问父线程上下文。

标签: java threadpool thread-local inherited


【解决方案1】:

我根据需要编写了这些方法。

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.ThreadPoolExecutor;

public class EnvUtils {
    /**
     * Extract the current inheritableThreadLocals map from the current thread.
     * Typical usage is in a threadpool, where:
     * <ul>
     * <li>You run {@link EnvUtils#extract()} in the running thread, to store
     * the information somewhere
     * <li>You create a method {@link ThreadPoolExecutor#beforeExecute()} in which
     * you run {@link EnvUtils#copy(Object)} with the above-stored information.
     * </ul>
     *
     * @return The current inheritableThreadLocals of the current thread
     */
    public static Object extract() {
        Object toreturn = null;
        try {
            // get field descriptor
            Field inthlocalsField = Thread.class.getDeclaredField("inheritableThreadLocals");
            inthlocalsField.setAccessible(true);
            //the object stored there
            Object inthlocalsMap = inthlocalsField.get(Thread.currentThread());
            // no need to copy, it will be done by the copy() method below
            toreturn = inthlocalsMap;
        } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
            // This may happen in a different Java implementation
            throw new RuntimeException(e);
        }
        return toreturn;
    }

    /**
     * Replaces the field inheritableThreadLocals of the current thread with the values provided.<br/>
     * It is the same as if the current thread was just created from the thread whose <code>stored</code>
     * values come from.<br/>
     * Must be called in the thread which want to inherit from given {@link inheritableThreadLocals} map.<br/>
     * <b>Note 1:</b> This does not modify non-inheritable thread locals<br/>
     * <b>Note 2:</b> This delete all previous values of {@link inheritableThreadLocals} in the current thread<br/>
     *
     * @param stored
     *            The stored inheritableThreadLocals value, coming from the extract() method
     */
    public static void copy(final Object stored) {
        try {
            // find ThreadLocalMap class
            String threadLocalClassName = ThreadLocal.class.getName();
            Class<?> threadLocaLMapClass = Class.forName(threadLocalClassName + "$ThreadLocalMap");
            // check that given object is an instance of the class
            if (stored == null || !threadLocaLMapClass.isInstance(stored)) {
                throw new IllegalArgumentException("Given object is not a ThreadLocalMap: " + stored);
            }
            // get constructor of ThreadLocalMap
            Constructor<?> creator = threadLocaLMapClass.getDeclaredConstructor(threadLocaLMapClass);
            creator.setAccessible(true);
            // get field descriptor of the thread
            Field inthlocalsField = Thread.class.getDeclaredField("inheritableThreadLocals");
            inthlocalsField.setAccessible(true);
            // create new inherited map
            Object newObj = creator.newInstance(stored);
            // set it to the current thread
            inthlocalsField.set(Thread.currentThread(), newObj);

        } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | NoSuchFieldException
                | IllegalAccessException | IllegalArgumentException | InvocationTargetException
                | InstantiationException e) {
            // This may happen in a different Java implementation
            throw new RuntimeException(e);
        }

    }

}

EnvUtils.extract() 返回对当前线程的inheritableThreadLocals 映射的引用。

现在,当您创建要在ThreadPool 中调用的Runnable 时,只需将其存储在inheritableThreadInfo = EnvUtils.extract() 字段中,并在其run() 方法中调用EnvUtils.copy(inheritableThreadInfo)

注意:此解决方案使用了大量反射,因此它受制于 Java 实现。我在 Oracle Java 1.8 上进行了测试。

【讨论】:

    【解决方案2】:

    如果我们这样配置 ThreadPoolExecutor

    new ThreadPoolExecutor(0, 2, 0L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());
    

    它每次都会创建一个新的线程,因此会继承InheritableThreadLocals,但它几乎不能称为ThreadPoolExecutor

    【讨论】:

    • 好的。是的,在这种情况下,这将不是一个线程池。关键是我们没有使用 ThreadPoolExecutor 来管理线程。我们使用 javax.resource.spi.work.WorkManager 的 IBM 实现来管理器线程。
    • 再补充一点,问题可以简化为,当线程池中的线程执行给定的线程时,有什么方法可以将父线程上下文中的 InhertiedThreadLocals 获取到子线程上下文中可以运行吗?
    猜你喜欢
    • 1970-01-01
    • 2011-11-09
    • 2013-12-22
    • 1970-01-01
    • 2011-09-29
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 2011-10-10
    相关资源
    最近更新 更多