使用currentHashMap vs Hashmap

时间:2019-01-25 05:27:57

标签: java multithreading

 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,因此{{1} }将放在第一位,之后thread1将覆盖thread2的内容。
这种行为正确吗?
就我而言,我希望在map.get完成后返回相同的值,因此我认为使用thread1 synchronizing 是首选。

1 个答案:

答案 0 :(得分:9)

使用CHM的原子computeIfAbsent()方法,您不必担心同步:

return map.computeIfAbsent(context, SampleClass::new);