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:
- suppose method
ensurefuture
not synchronized in case possible 1 thread invokescontainskey
returnstrue
before next line executed thread may remove entry respective key. can lead race conditioncheck-then-act
scenario. check this well. - also using
chachedfutures.put(value, ftr)
imo should usechachedfutures.putifabsent(value, ftr)
. methodif 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
Post a Comment