java - concurrent hashmap and copyonwritearraylist -


i trying populate cache hold key/value concurrenthashmap.

i assuming using copyonwritearraylist takes care of concurrency , have value key, missing in below code , overriding values when multiple threads executing.

if (testmap.get(id) == null) {    copyonwritearraylist<string> copyarr = new copyonwritearraylist<string>();    copyarr.add("add value");    testmap().putifabsent(id, copyarr); } else {                        testmap.put(id,testmap.get().add("append value")); } 

how protect code creates copyonwritearraylist multiple threads.

here revised version of code per suggestions below.

copyonwritearraylist<subscriber> subscriberarr =  cacheutils.getsubscribermap().get(syncdet.getcardnumber());  if (subscriberarr == null) {  subscriberarr = new copyonwritearraylist<subscriber>(); copyonwritearraylist<subscriber> refarr =   cacheutils.getsubscribermap().putifabsent(syncdet.getcardnumber(), subscriberarr);  if (refarr != null) {  subscriberarr = refarr; }  }  subscriberarr.add(syncdet.getsubscriber()); 

on iterating subscriber map dont see value object. size 0 .

you need first retrieve appropriate list populate it. like:

list<string> copyarr = testmap.get(id); if (copyarr == null) {     copyarr = new copyonwritearraylist<string>();     list<string> inmap = testmap.putifabsent(id, copyarr);     if (inmap != null) copyarr = inmap; // in map } copyarr.add("add value"); 

that way put new list in map if there wasn't 1 , add item whatever list has made map.


Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -