我正在使用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/