如果我从多个线程读取HashMap会有问题吗?

Nic*_*rta 3 java spring multithreading hashmap

我有许多带有自己的哈希图的服务,我的哈希图是不可变的,它们在初始化块中进行初始化。因此,所有线程都将读取哈希图,但不会对其进行写入。

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

使用HashMap来做这件事有什么问题吗?我应该使用其他课程吗?为什么?

这是我正在谈论的内容的一个例子:

@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.
    
}
Run Code Online (Sandbox Code Playgroud)

Bur*_*dar 5

HashMap 对于只读并发访问是安全的。确保在线程启动之前初始化哈希图,并且只要没有其他线程写入它们,就可以从多个线程使用它们,而不会出现任何竞争条件。