gpt4 book ai didi

java - NullPointerException 可能与 InheritableThreadLocal 有关

转载 作者:行者123 更新时间:2023-11-30 04:55:56 24 4
gpt4 key购买 nike

我想使用InheritableThreadLocal来存储一些变量。所以我写了一些这样的代码:

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");
}

这意味着您使用受支持的方式来初始化线程本地值。

关于java - NullPointerException 可能与 InheritableThreadLocal 有关,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8550663/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com