Tuesday, 15 May 2012

java - Thread safe Map of Queues -



java - Thread safe Map of Queues -

i want implement thread safe map of queues.

i intent start empty map. if key not exist, want create new map entry new queue. if key exist, want add together queue. proposed implementation follows:

import java.util.map; import java.util.concurrent.concurrenthashmap; import java.util.concurrent.concurrentlinkedqueue; public class stackoverflowexample { private final map<string, concurrentlinkedqueue<string>> map = new concurrenthashmap<>(); public void addelementtoqueue(string key, string value){ if (map.containskey(key)){ map.get(key).add(value); } else{ concurrentlinkedqueue<string> queue = new concurrentlinkedqueue<>(); queue.add(value); map.put(key, queue); } } }

my concern is when multiple threads effort add together new value map, first set new map entry new queue, sec wait, , set new queue key, rather adding queue. concurrency / concurrency api knowledge slim @ best. perhaps concurrency in-place avoid this? advice much appreciated.

this pattern has been posted many times on (efficiently adding concurrent map):

queue<string> q = map.get(key); if(q == null) { q = new concurrentlinkedqueue<string>(); queue<string> curq = map.putifabsent(key, q); if(curq != null) { q = curq; } } q.add(value);

java multithreading queue concurrenthashmap

No comments:

Post a Comment