[英]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);
}
}
在多线程环境中,如果两个线程将map.get(context)
作为null ,则两个线程都将创建cls
,并且put将被阻塞,因此thread1
将首先放置,之后thread2
将覆盖thread1
放置的thread1
。
这种行为是否正确?
在我的情况下,我想在map.get完成时返回相同的值,因此我看到使用HashMap
并且首选同步它。
使用CHM的原子computeIfAbsent()
方法,您不必担心同步:
return map.computeIfAbsent(context, SampleClass::new);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.