java - ConcurrentHashMap as singletone cache with synchronized -


how think, do need use synchronized block better optimization of access instance of ad? instance of ad.class can retrieved different threads. synchronized helps instance in 1 time 1 operation concurrenthashmap. concurrenthashmap store values volatile. use on java 1.7 android, computeifabsent available in java 1.8.

it great detailed answer, why not or why yes. thank you!

public final class ad {      private final static map<string, ad> ads = new concurrenthashmap<>();      public static ad get(@nonnull string appid) {         if (appid == null) appid = "";          boolean containsad = ads.containskey(appid);          ad localinstance = containsad ? ads.get(appid) : null;          if (localinstance == null) {             synchronized (ad.class) {                  containsad = ads.containskey(appid);                  localinstance = containsad ? ads.get(appid) : null;                  if (localinstance == null) {                     localinstance = new ad();                     localinstance.setadid(appid);                     ads.put(appid, localinstance);                 }             }         }         return localinstance;     }      private ad() {     } } 

update: help. replaced concurrenthashmap hashmap.

this not quite optimal. if multiple threads try initialize values @ same time, block each other, if looking different keys.

you should use concurrenthashmap.computeifabsent check add , create missing ones in single step. way not create ads aren't used, , 2 threads block each other if they're trying initialize same entry:

public static ad get(@nonnull string appid) {     if (appid == null) appid = "";      return ads.computeifabsent(appid, ad::new); }  private ad(string appid) {     this();     setadid(appid); } 

Comments

Popular posts from this blog

javascript - Create a stacked percentage column -

Optimising Firebase database by automatically overwriting data -

javascript - Angular UI-Grid customTemplate directive causing rows to load slowly/? -