java - Cache using ConcurrentHashMap -


i have following code:

public class cache {      private final map map = new concurrenthashmap();      public object get(object key) {          object value = map.get(key);         if (value == null) {             value = new someobject();             map.put(key, value);         }          return value;     } } 

my question is: put , get methods of map thread safe, since whole block in not synchronized - multiple threads add same key twice?

put , get thread safe in sense calling them different threads cannot corrupt data structure (as, e.g., possible normal java.util.hashmap).

however, since block not synchronized, may still have multiple threads adding same key: both threads may pass null check, 1 adds key , returns value, , second override value new 1 , returns it.


Comments

Popular posts from this blog

c++ - QTextObjectInterface with Qml TextEdit (QQuickTextEdit) -

javascript - angular ng-required radio button not toggling required off in firefox 33, OK in chrome -

xcode - Swift Playground - Files are not readable -