java - ConcurrentHashMap 等待键可能吗?

标签 java collections guava

我有多线程通信。 1 线程正在向其他线程分派(dispatch)数据。

主线程正在推送数据:

主线程: ConcurrentHashMap map = Global.getInstance().getMap(); //将数据推送到其他线程 map.put(1,"测试");

线程 1: 字符串数据 = map.get(1); //直接返回null,但我想等到数据推送

如果主线程没有推送任何数据,线程 1 返回 null。 但我想等到我得到数据, 我怎么等?

TransferQueue 不是我当前实现的好的解决方案。 我必须处理 ConcurrentHashMap。

有人知道解决办法吗?

最佳答案

你可以创建一个 BlockingMap,像这样;根据使用情况,您还应该设置一种机制来删除未使用的键和与其关联的队列,以避免内存泄漏。

public class BlockingMap<K, V> {
    private final Map<K, BlockingQueue<V>> map = new ConcurrentHashMap<>();

    private synchronized BlockingQueue<V> ensureQueueExists(K key) {
        //concurrentMap.putIfAbsent would require creating a new
        //blocking queue each time put or get is called
        if (map.containsKey(key)) {
            return map.get(key);
        } else {
            BlockingQueue<V> queue = new ArrayBlockingQueue<>(1);
            map.put(key, queue);
            return queue;
        }
    }

    public boolean put(K key, V value, long timeout, TimeUnit timeUnit) {
        BlockingQueue<V> queue = ensureQueueExists(key);
        try {
            return queue.offer(value, timeout, timeUnit);
        } catch (InterruptedException e) {
            throw new IllegalStateException(e);
        }
    }

    public V get(K key, long timeout, TimeUnit timeUnit) {
        BlockingQueue<V> queue = ensureQueueExists(key);
        try {
            return queue.poll(timeout, timeUnit);
        } catch (InterruptedException e) {
            throw new IllegalStateException(e);
        }
    }
}

从 Java 8 开始,ensureQueueExists 可以这样写:

private synchronized BlockingQueue<V> ensureQueueExists(K key) {
    return map.computeIfAbsent(key, k -> new ArrayBlockingQueue<>(1));
}

关于java - ConcurrentHashMap 等待键可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23917818/

相关文章:

java - 安卓和Java : Edit Text with multiple language support but few special characters

linq-to-sql - 我们可以将 ISingleResult<T> 转换为 IList<T>

android - 在 Kotlin 中对 ArrayList 进行排序

java - 使用 Jackson 将列表序列化为 xml,无需注释?

java - 仅在 Java 中对键进行排序的 Multimap

java - 如何在 Java 中生成顺序整数的列表或数组?

java - 如何从 Activity 中获取偏好值?

java - 根据给定的数字数组创建几乎唯一的标识符

java - 如何使用 Apache Camel 测量耗时

java - 不兼容的类型 String 和 Char