java - 线程本地间歇性返回 null

标签 java multithreading thread-local

我正在使用ThreadLocal来存储上下文变量。我的组件是一个 SOA - Rest 组件。问题是 threadLocal 间歇性地返回 null。我确信在使用它之前我已经填充了它。我正在从 JAX-RS 响应过滤器中清除它。

static final 修饰符会导致此问题吗?只需将其指定为 InheritableThreadLocal 就可以让所有子线程使用 threadLocal 吗?

import java.util.Map;

/**
 * Contains the context object and 
 */
public class ContextHolder {

    private static final ThreadLocal<Map<String, Object>> threadLocal = new InheritableThreadLocal<Map<String, Object>>();

    /**
     * Private constructor so that nobody can create an instance.
     */
    private ContextHolder() {
    }

    /**
     * Initializes the threadlocal with the passed map.
     * 
     * @param context - 
     */
    public static void initConext(Map<String, Object> context) {
        threadLocal.set(context);
    }

    /**
     * Returns the context from this thread.
     * 
     * @return Context
     */
    public static Map<String, Object> getContext() {
        return threadLocal.get();
    }

    /**
     * Clears the context from the threadlocal.
     */
    public static void clearConext() {
        threadLocal.remove();
    }

}

最佳答案

static final 修饰符不应导致此问题。所有ThreadLocal对象可供所有子线程使用;只是它们的内容在每个线程的基础上有所不同。安InheritableThreadLocal不同之处在于子线程的初始值是继承的,而不是最初设置为 null。请注意,仅继承初始值,不会继承父线程中的后续修改。

当尝试将值从父线程传递到子线程时,您的代码同步方式很可能存在错误。在处理多个线程时,“之前”具有非常复杂且有时违反直觉的含义,尤其是在早期版本的 Java 中。

关于java - 线程本地间歇性返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31979069/

相关文章:

java - 使用 JPA 的 Spring 安全性。如何配置applicationContext-security.XML文件?(使用DaoAuthenticationProvider)

C++ : Handle thread-local object destruction

Java 密码学扩展和无限力量

Java String.matches 正则表达式

java - 数组的 volatile 数组

c++ - 有没有办法查看每个线程进程的虚拟内存使用情况?

java - 将线程局部变量传递给 JUnit 测试

java - 这里需要用到ThreadLocal吗?

java - JComboBox 到字符串

java - 性能Image.SCALE_DEFAULT与Image.SCALE_SMOOTH