【发布时间】:2021-03-19 22:35:43
【问题描述】:
我有许多带有他自己的哈希图的服务,我的哈希图是不可变的,它们在初始化程序块中被初始化。所以所有线程都将读取哈希图,但从不写它们。
我的服务是 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.
}
【问题讨论】:
-
HashMap不是线程安全的。你应该考虑ConcurrentHashMap或SynchronizedMap。 -
你应该没问题,只要 HashMap 永远不会被写入,否则考虑使用 ConcurrentHashMap。
-
如果它是只读的,HashMap 没问题,但我会在构造函数中实例化。如果地图会发生变异,请考虑 ConcurrentHashMap
-
@Idos 如果
HashMap已正确发布且发布后从未写入,则不需要。
标签: java spring multithreading hashmap