ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

java:并发集合

2019-09-02 13:00:10  阅读:201  来源: 互联网

标签:java concurrency guava map


我正在尝试找到一个或多个要使用的并发集合,我可以实现以下行为(这些名称是出于类比目的而设计的):

/**
 * Acts as a broker for a concurrent hash map that stores its keys in order 
 * of submission. At shipping time, the concurrent map is "sealed" 
 * (picture a truck with its cargo door being closed)
 * and its contents presented as an immutable map, and is replaced 
 * by a new concurrent map ready to accept values.
 *
 * Consumers of this class that submit information to it, are expected to 
 * know that this contains a concurrent collection, and should use the 
 * compareAndSet paradigm, e.g. the following:
 *
 * LoadingDock loadingDock = ...
 * boolean done = false;
 * while (!done)
 * {
 *    V oldValue = loadingDock.get();
 *    V newValue = computeNewValue(oldValue, otherInformation);
 *    if (oldValue == null)
 *       done = loadingDock.putIfAbsent(newValue) == null;
 *    else
 *       done = loadingDock.replace(oldValue, newValue) == oldValue;
 * }
 *    
 *
 * Keys and values must be non-null. Keys are not ordered.
 */
class LoadingDock<K,V>
{
    /**
     * analogous to ConcurrentMap's replace, putIfAbsent, and get methods
     */
    public boolean replace(K key, V oldValue, V newValue);
    public V putIfAbsent(K key, V value);
    public V get(K key)

    /* see above */
    public Map<K,V> ship();
}

我有两个问题.

一个是Java和Guava都不包含ConcurrentLinkedHashMap.这让我想知道为什么不 – 也许我错过了这样一个野兽的微妙之处.看起来我可以通过使用一个类来装饰ConcurrentHashMap来自己创建一个类,如果调用了putIfAbsent()并且返回null,那么该类会向列表添加一个键 – 我不需要在ConcurrentHashMap中使用任何其他方法.上面,除了通过调用putIfAbsent()之外,没有办法向地图添加新密钥.

另一个更隐蔽的问题是,我似乎无法想到如何在不阻塞同步的情况下实现ship() – 当调用ship()时,LoadingDock需要将所有新调用指向新映射,并且可以返回旧映射,直到确定所有并发写入完成为止. (否则我只会使用AtomicReference来保存并发映射.)

有没有办法做到这一点无需同步?

解决方法:

您可以使用ConcurrentSkipListMap并提供自己的比较器,根据时间戳对条目进行排序.有人认为没有ConcurrentLinkedMap,因为没有任何特别好的方法来实现它,这比同步常规方法要好得多.

对于ship()方法,只需使用打开了公平模式的ReadWriteLock.想要添加到地图的线程,获取Read锁(我知道的奇怪语义,但它是如何工作的,将其视为对地图的实际引用的读取模式,然后正常使用),以便尽可能多地使用想要可以同时添加.在ship方法中,您获取了写锁定,它将阻止其他任何人在您导出并创建新地图时更改地图.公平模式使得你“切断”加法器尽可能接近于调用ship()并让现有的加法器完成.

标签:java,concurrency,guava,map
来源: https://codeday.me/bug/20190902/1791297.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有