Java 线程局部间歇返回null

Java 线程局部间歇返回null,java,multithreading,thread-local,Java,Multithreading,Thread Local,我正在使用ThreadLocal存储上下文变量。我的组件是一个SOA-rest组件。问题是threadLocal间歇性返回null。我确信在使用它之前我已经填充了它。我正在从JAX-RS repsonse过滤器中清除它 静态final修饰符是否会导致此问题?只需将其指定为InheritableThreadLocal,threadLocal是否可用于所有子线程 import java.util.Map; /** * Contains the context object and */ pu

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

静态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();
    }

}
import java.util.Map;
/**
*包含上下文对象和
*/
公共类上下文持有者{
private static final ThreadLocal ThreadLocal=new InheritableThreadLocal();
/**
*私有构造函数,这样任何人都不能创建实例。
*/
私有上下文持有者(){
}
/**
*使用传递的映射初始化threadlocal。
* 
*@param上下文-
*/
公共静态void initConext(映射上下文){
threadLocal.set(上下文);
}
/**
*从该线程返回上下文。
* 
*@returncontext
*/
公共静态映射getContext(){
返回threadLocal.get();
}
/**
*从threadlocal中清除上下文。
*/
公共静态void clearConext(){
threadLocal.remove();
}
}

静态final修饰符不应导致此问题。所有
ThreadLocal
对象对所有子线程都可用;只是每个线程的内容不同而已。不同之处在于子线程的初始值是继承的,而不是最初设置为null。请注意,仅继承初始值,而不继承父线程中的后续修改


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

它是Java附带的。langAjay哇哇:)您能否澄清问题在于
映射是
null
,而不是映射返回
null
(即空)?