gpt4 book ai didi

java - 将对象存储在静态类中的散列中是否安全,使用线程 ID 检索该特定线程的值?

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:32:43 26 4
gpt4 key购买 nike

我正在对我编写的一些代码进行一些更改,以尝试将其更改为多线程解决方案。我的主类中的一些元素最初是静态的,并且必须作为我所做更改的一部分进行更改。我想将它们存储在 HashMap 中,使用 Thread 的 Id 作为检索项目的键 - 这样我就可以存储对 的引用>Runnable 类,并使用 getters/setters 访问给定线程的所需属性。我定义了以下代码来执行此操作:

import java.util.HashMap;

public class ThreadContext {

private static HashMap<String, HashMap<String, Object>> tContext;

static {
initThreadContext();
}

public static void initThreadContext() {
String id = String.valueOf(Thread.currentThread().getId());
tContext = new HashMap<>();
}

public static void setObject(String key, Object o) {
String id = String.valueOf(Thread.currentThread().getId());
HashMap<String, Object> hash = tContext.get(id);

if( hash == null ) {
hash = new HashMap<>();
tContext.put(id, hash);
}

hash.put(key, o);
}

public static Object getObject(String key) {
String id = String.valueOf(Thread.currentThread().getId());
HashMap<String, Object> hash = tContext.get(id);

if( hash == null ) {
hash = new HashMap<>();
tContext.put(id, hash);
}

Object o = hash.get(key);

return o;
}
}

我的问题是:这样做安全吗,还是我应该尝试寻找另一种方法来做到这一点?我的示例似乎工作正常,但我不确定是否会因此而产生任何其他副作用。

编辑:用法示例:

Foo foo = ((Foo)ThreadContext.getObject(Foo.CLASS_IDENTIFIER));

foo.doStuff();

最佳答案

已经有一种方法可以使用 JDK 的 ThreadLocal 来做到这一点,它为每个(本地)线程存储不同的引用。

关于java - 将对象存储在静态类中的散列中是否安全,使用线程 ID 检索该特定线程的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35116955/

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