gpt4 book ai didi

java - 从多线程读取一个HashMap会有问题吗?

转载 作者:行者123 更新时间:2023-12-03 12:48:04 25 4
gpt4 key购买 nike

我有很多服务都有他自己的 HashMap ,我的 HashMap 是不可变的,它们在初始化程序 block 中被初始化。所以所有线程都将读取 HashMap ,但不会写入它们。

我的服务是 Spring 的组件,所以它们是“Spring Singletons”。

这个用HashMap有什么问题吗?我应该使用其他类(class)吗?为什么?

这是我在说什么的一个例子:

@Service
public class TrackingServiceOne extends TrackingService {


Map<Integer, String> mapCreditos = new HashMap<Integer, String>();
Map<Integer, String> mapDeudas = new HashMap<Integer, String>();
Map<Integer, String> mapEjemplo = new HashMap<Integer, String>();

{

mapCreditos.put(1, "hi");
mapCreditos.put(2, "example");
// And like this I will populate each map.

}



// My methods will read the maps, never write them.

}

最佳答案

HashMap 对于只读并发访问是安全的。确保在线程启动之前 hashmaps 被初始化,并且只要没有其他线程写入它们,它们就可以在没有任何竞争条件的情况下从多个线程使用。

关于java - 从多线程读取一个HashMap会有问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66716385/

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