Xephonia
Xephonia

Reputation: 163

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.

Upvotes: 2

Views: 89

Answers (1)

shmosel
shmosel

Reputation: 50756

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

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

Upvotes: 9

Related Questions