private static final Map<String, SampleClass> map = new
ConcurrentHashMap<>();
public static SampleClass getsampleclass(String context) {
if( map.get(context) != null) {
return map.get(context);
} else {
SampleClass cls = new SampleClass(context);
map.put(context, cls);
}
}
在多线程环境下,如果两个线程都将map.get(context)
作为null,那么两个线程都会创建cls
, 并且 put 将被阻塞,因此 thread1
将首先放置,然后 thread2
将覆盖 thread1
放置的内容。
这种行为是否正确?
在我的例子中,我希望在完成 map.get 时返回相同的值,因此我看到使用 HashMap
和 synchronizing 它是首选。
最佳答案
使用 CHM 的原子 computeIfAbsent()
方法,您不必担心同步问题:
return map.computeIfAbsent(context, SampleClass::new);
关于java - 使用 concurrentHashMap 与 Hashmap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54359428/