[英]Using concurrentHashMap vs Hashmap
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);
}
}
In multi-threaded environment, if two threads get map.get(context)
as null , then both the threads will create cls
, and put will blocked, therefore thread1
will put first and after it thread2
will override what was put by thread1
. 在多线程环境中,如果两个线程将
map.get(context)
作为null ,则两个线程都将创建cls
,并且put将被阻塞,因此thread1
将首先放置,之后thread2
将覆盖thread1
放置的thread1
。
Is this behavior correct ? 这种行为是否正确?
In my case, I want same value to be returned when map.get is done, hence i see using HashMap
and synchronizing it is preferred. 在我的情况下,我想在map.get完成时返回相同的值,因此我看到使用
HashMap
并且首选同步它。
使用CHM的原子computeIfAbsent()
方法,您不必担心同步:
return map.computeIfAbsent(context, SampleClass::new);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.