Java NullPointerException可能与InheritableThreadLocal相关
我想使用InheritableThreadLocal来存储一些变量。所以我写了一些这样的代码:Java NullPointerException可能与InheritableThreadLocal相关,java,nullpointerexception,thread-local,Java,Nullpointerexception,Thread Local,我想使用InheritableThreadLocal来存储一些变量。所以我写了一些这样的代码: public class ThreadContext { private static ThreadLocal current = new InheritableThreadLocal(); public static HashMap getContext() { if (current.get() == null) { createC
public class ThreadContext
{
private static ThreadLocal current = new InheritableThreadLocal();
public static HashMap getContext()
{
if (current.get() == null) {
createContext();
}
return (HashMap) current.get();
}
public static void createNewContext(){
createContext();
}
public static IClientContext getClientContext()
{
return (IClientContext) ThreadContext.getContext().get("CLIENT_CONTEXT");
}
public static void setClientContext(IClientContext ctx) {
ThreadContext.getContext().put("CLIENT_CONTEXT", ctx);
}
private static void createContext()
{
current.set(new HashMap());
}
}
但当其他代码调用getClientContext时,NullPointerException偶尔会发生:
java.lang.NullPointerException
at com.xxx.util.ThreadContext.getClientContext(ThreadContext.java:19)
看起来getContext返回了一个空值。但在getContext中,它不能返回null。
因为如果get返回null,它将创建一个新的
public static HashMap getContext()
{
if (current.get() == null) {
createContext();
}
return (HashMap) current.get();
}
以前有人遇到过这个问题吗?或者有什么想法吗?我不确定这是否能解决您的问题,但写这篇文章更清晰的方法是
public class ThreadContext {
private static ThreadLocal<Map<String, IClientContext>> current = new InheritableThreadLocal<Map<String, IClientContext>>() {
protected Map<String, IClientContext> initialValue() {
return new LinkedHashMap<String, IClientContext>();
}
};
public static IClientContext getClientContext(){
return ThreadContext.getContext().get("CLIENT_CONTEXT");
}
公共类线程上下文{
private static ThreadLocal current=new InheritableThreadLocal(){
受保护的映射初始值(){
返回新的LinkedHashMap();
}
};
公共静态IClientContext getClientContext(){
返回ThreadContext.getContext().get(“客户端上下文”);
}
这意味着您将使用受支持的方式初始化线程本地值。+1使代码线程安全。OP的代码可以返回两个不同的映射到两个线程。但我不知道他如何获得NPE。@JBNizet同意,但如果他正在做某事,他不会说应该替换它。@PeterLawrey感谢您的建议。我还想知道为什么要使用LinkedHashMap吗?我更喜欢使用LHM,因为它保留了插入顺序。我发现这使日志记录和调试更容易。例如,当添加条目时,它总是在末尾。如果添加排序键,它们保持相同的顺序,以便更容易检查其正确性。谢谢` s!您的回答用simpleDateFormat在Threa中解决了我的问题在我出生之前,我也有NPE。