java - What kind of the Map interface I should use? -


i need make following class thread-safe:

//shared among threads public class sharedcache {      private map<object, future<collection<integer>>> chachedfutures;     {         chachedfutures = new concurrenthashmap<>(); //not sure     }      public future<collection<integer>> ensurefuture(object value,                                                      futurefactory<collection<integer>> ff){         if(chachedfutures.containskey(value))             return chachedfutures.get(value);         future<collection<integer>> ftr = ff.create();         chachedfutures.put(value, ftr);         return ftr;     }      public future<collection<integer>> remove(object value){         return chachedfutures.remove(value);     }  } 

after reading article concurrenthashmap class it's still difficult me make right decision.

firstly, tended make methods ensurefuture , remove synchronized. , work, performance standpoint not because of mutually-exclusing.

i don't know exact (even approximately) amount of threads having access cache simultaneously , size of cache. taking account

resizing or other kind of hash table relatively slow operation

i didn't specify initial size of map. concurrencylevel parameter. justified use concurrenthashmap here or synchronized methods enough?

you have following methods:

     public future<collection<integer>> ensurefuture(object value,                                                      futurefactory<collection<integer>> ff){         if(chachedfutures.containskey(value))             return chachedfutures.get(value);         future<collection<integer>> ftr = ff.create();         chachedfutures.put(value, ftr);         return ftr;     }      public future<collection<integer>> remove(object value){         return chachedfutures.remove(value);     } 

there points noticed:

  1. suppose method ensurefuture not synchronized in case possible 1 thread invokes containskey returns true before next line executed thread may remove entry respective key. can lead race condition check-then-act scenario. check this well.
  2. also using chachedfutures.put(value, ftr) imo should use chachedfutures.putifabsent(value, ftr) . method if specified key not associated value (or mapped null) associates given value , returns null, else returns current value. using can avoid contains check.

is justified use concurrenthashmap here or synchronized methods enough?

it depends chm needs more memory compared hashmap due lot of bookkeeping activities etc. alternative use collections.synchronizedmap provide synchronization on regular hashmap.


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -