线程安全队列的映射 [英] Thread safe Map of Queues

查看:99
本文介绍了线程安全队列的映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现线程安全的队列映射.

I want to implement a thread safe Map of Queues.

我打算从一个空的地图开始.如果键不存在,我想用一个新的队列创建一个新的Map条目.如果密钥确实存在,我想添加到队列中.我建议的实现如下:

I intent to start with an empty Map. If the key does not exist, I want to create a new Map entry with a new Queue. If the key does exist, I want to add to the Queue. My proposed implementation is as 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);
        }           
    }    
}

我担心的是,当多个线程试图向Map添加新值时,第一个线程将使用新的Queue放置一个新的Map条目,第二个线程将等待,然后为该键放置一个新的Queue,而不是而不是添加到队列中.我的并发性/并发性API知识充其量是最薄弱的.也许并发可以避免这种情况?建议将不胜感激.

My concern is that is when multiple threads attempt to add a new value to the Map, the first will put a new Map entry with a new Queue, the second will wait, and then put a new Queue for the key, rather than adding to the Queue. My concurrency / concurrency API knowledge is slim at best. Perhaps the concurrency is in-place to avoid this? Advice would be much appreciated.

推荐答案

此模式可能已在SO上多次发布(有效地添加到并发映射中):

This pattern has probably been posted many times on SO (efficiently adding to a 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);

这篇关于线程安全队列的映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆