Java 使用concurrentHashMap与Hashmap private静态最终映射=新建 ConcurrentHashMap(); 公共静态SampleClass getsampleclass(字符串上下文){ if(map.get(context)!=null){ 返回map.get(上下文); }否则{ SampleClass cls=新的SampleClass(上下文); map.put(上下文,cls); } }

Java 使用concurrentHashMap与Hashmap private静态最终映射=新建 ConcurrentHashMap(); 公共静态SampleClass getsampleclass(字符串上下文){ if(map.get(context)!=null){ 返回map.get(上下文); }否则{ SampleClass cls=新的SampleClass(上下文); map.put(上下文,cls); } },java,multithreading,Java,Multithreading,在多线程环境中,如果两个线程将map.get(context)设为null,则两个线程都将创建cls,并且put将被阻止,因此thread1将放在第一位,而thread2将覆盖thread1放置的内容 这种行为正确吗? 在我的例子中,我希望在map.get完成时返回相同的值,因此我认为最好使用HashMap并对其进行同步 使用CHM的原子方法,您就不必担心同步问题: private static final Map<String, SampleClass> map = new C

在多线程环境中,如果两个线程将
map.get(context)
设为null,则两个线程都将创建
cls
,并且put将被阻止,因此
thread1
将放在第一位,而
thread2
将覆盖
thread1
放置的内容
这种行为正确吗?
在我的例子中,我希望在map.get完成时返回相同的值,因此我认为最好使用
HashMap
并对其进行同步

使用CHM的原子方法,您就不必担心同步问题:

 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);
     }
 }

同意。。这是去的路move@Geeta读取通常不需要使用CHM进行阻止。它在java8中进行阻止
return map.computeIfAbsent(context, SampleClass::new);