Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.
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.

like image 263
Xephonia Avatar asked May 31 '26 20:05

Xephonia


1 Answers

Use CHM's atomic computeIfAbsent() method and you won't have to worry about synchronization:

return map.computeIfAbsent(context, SampleClass::new);
like image 84
shmosel Avatar answered Jun 03 '26 09:06

shmosel